Springboot简介

  1. springboot用来简化Spring+SpringMVC+Mybatis框架的开发过程。采用大量的默认设置简化开发过程,可以非常容易和快速的创建基于Spring框架的应用程序,让编码变简单了,配置变简单了,部署变简单了,监控变简单了。
  2. Springboot的特性

a)      Springboot能够快速创建基于Spring的应用程序

b)      能够使用java main方法启动内嵌的Tomcat,Jetty服务器运行Springboot程序,不需要部署war文件。

c)      提供约定的start POM来简化Maven配置,让Maven的配置变得简单。

d)      根据项目的Maven依赖配置,Springboot自动配置spring,springmvc等

e)      提供了程序的健康检查等功能

f)       基本可以完全不用XML配置文件,采用注解配置

  1. Springboot核心

a)      自动配置:针对很多spring应用程序和常见的应用功能,springboot能自动提供相关配置

b)      起步依赖:告诉springboot需要什么功能,它就能引入需要的依赖库

 

Springboot的注解

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})和@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})用来取消springboot对数据源和配置的注入

 

@RestController    放在类上,整个类返回的都是json对象

 

@EnableDubbo    放在springboot入口处类上方,用来确保zookeeper配置文件被执行

IDEA使用SPRINGBOOT

1.Create New Project

 

 

 

2.选择Spring Initializr,配置自己的SDK(就是java的JDK)

 

 

 

3.填写好Maven

 

 

 

4.选择其他的应用

 

 

 

5.选择project(相当于eclipse里的工作空间)

 

 

 

6.创建好springboot后的界面

 

 

 

7.编写控制层

 

 

 

8.启动springboot自带的tomcat

 

 

 

9.通过地址127.0.0.1:8080/test访问

 

 

 

10.继续看application.properties属性文件

 

 

 

 

SPRINGBOOT与SPRINGMVC(有Restfull风格)

package com.kfs.springboot.controller;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

 

@Controller

public class TestController {

    @GetMapping("testGet")     //相当于:@RequestMapping(value = "testGet",method = RequestMethod.DELETE.GET)

    @ResponseBody

    public String testGet(){

        return "testGet";

    }

 

    @PostMapping("testPost")    //相当于:@RequestMapping(value = "testPost",method = RequestMethod.DELETE.POST)

    @ResponseBody

    public String testPost(){

        return "testPost";

    }

 

    @PutMapping("testPut")      //相当于:@RequestMapping(value = "testPut",method = RequestMethod.DELETE.PUT),springboot不用加过滤器

    @ResponseBody

    public String testPut(){

        return "testPut";

    }

 

    @DeleteMapping("testDelete")    //相当于:@RequestMapping(value = "testDelete",method = RequestMethod.DELETE.DELETE),springboot不用加过滤器

    public String testDelete(){

        return "testDelete";

    }

}

 

IDEA不自动编译jsp,xml,html等文件需要在pom.xml下的build下加入resources标签:如写mybatis不加会导致绑定异常

<resources>

                     <resource>

                            <directory>src/main/java</directory>

                            <includes>

                                   <include>**/*.xml</include>

                            </includes>

                     </resource>

                     <resource>

                            <directory>src/main/resources</directory>

                            <includes>

                                   <include>**/*.*</include>

                            </includes>

                     </resource>

                     <resource>

                            <directory>src/main/webapp</directory>

                            <targetPath>META-INF/resources</targetPath>

                            <includes>

                                   <include>**/*.*</include>

                            </includes>

                     </resource>

              </resources>

 

Springboot集成JSP

1.在pom.xml加入jar包

<!--引入Spring Boot内嵌的Tomcat对JSP的解析包 因为springboot 中内嵌的Tomcat默认不支持jsp模板引擎的解析。

     默认支持Thymeleaf,FreeMark

-->

<dependency>

   <groupId>org.apache.tomcat.embed</groupId>

   <artifactId>tomcat-embed-jasper</artifactId>

</dependency>

<!-- servlet依赖的jar包start -->

<dependency>

   <groupId>javax.servlet</groupId>

   <artifactId>javax.servlet-api</artifactId>

</dependency>

<!-- servlet依赖的jar包start -->

 

<!-- jsp依赖jar包start -->

<dependency>

   <groupId>javax.servlet.jsp</groupId>

   <artifactId>javax.servlet.jsp-api</artifactId>

   <version>2.3.1</version>

</dependency>

<!-- jsp依赖jar包end -->

 

<!--jstl标签依赖的jar包start -->

<dependency>

   <groupId>javax.servlet</groupId>

   <artifactId>jstl</artifactId>

</dependency>

 

2.在springboot配置文件:application.properties添加视图解析器

#springmvc的视图解析器

spring.mvc.view.prefix=/

spring.mvc.view.suffix=.jsp

 

3.在src/main下创建一个目录webapp

 

Springboot和mybatis整合。

1.springboot和mybatis,mvc整合可以在创建时选择相应的应用。(第一种方法)

 

2.创建好项目后可以整合其他应用

a)      在pom.xml文件加入springboot和mybatis快速启动jar文件

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

        <dependency>

            <groupId>org.mybatis.spring.boot</groupId>

            <artifactId>mybatis-spring-boot-starter</artifactId>

            <version>2.1.1</version>

        </dependency>

 

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <scope>runtime</scope>

        </dependency>

 

b)      在springboot配置文件里配置数据源,加载映射文件

#配置数据源

spring.datasource.username=root

spring.datasource.password=123

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

#加载映射文件

mybatis.mapper-locations=classpath:com/springboot/springboottest/mapper/*.xml

 

c)      创建相应的bean,dao,service,controller代码

d)      在dao接口里需要加入@Mapper(把mapper文件和dao接口相联,只对这一个类有效)注解或在启动文件Application.java入口处加入@MapperScan("com.springboot.springboottest.dao")://把mapper文件和dao接口相联,对这一个包都有效。

e)      启动测试

 

springboot使用事物管理

  1. 在入口类中使用注解@EnableTransactionManagement开启事物支持
  2. 在访问数据库的Service方法上添加注解@Transactional。

springboot2.2版本只需要在service方法上添加注解@Transactional就可以了

 

Springboot使用通用Mapper

1.创建IDEA的Maven工程(带有web,mybatis,mysql的)

2.加入jar包

<!-- Common Mapper -->

        <dependency>

            <groupId>tk.mybatis</groupId>

            <artifactId>mapper-spring-boot-starter</artifactId>

            <version>2.0.2</version>

        </dependency>

 

3.配置属性文件

#配置数据源

spring.datasource.username=root

spring.datasource.password=123

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

4.创建实体类(需要通用Mapper的注解)

package com.kfs.bean;

 

import org.springframework.stereotype.Repository;

 

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

import java.io.Serializable;

 

@Table(name = "tb_user")

public class User  {

 

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

 

    private String userName;//通用Mapper可以把驼峰规则的大写字母变成_(下划线)加小写来使用

    private String password;

    private String name;

 

    public User() {

    }

 

    @Override

    public String toString() {

        return "User{" +

                "id=" + id +

                ", userName='" + userName + '\'' +

                ", password='" + password + '\'' +

                ", name='" + name + '\'' +

                '}';

    }

 

    public Long getId() {

        return id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getUserName() {

        return userName;

    }

 

    public void setUserName(String userName) {

        this.userName = userName;

    }

 

    public String getPassword() {

        return password;

    }

 

    public void setPassword(String password) {

        this.password = password;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public User(String userName, String password, String name) {

        this.userName = userName;

        this.password = password;

        this.name = name;

    }

}

 

5.dao层:springboot

package com.kfs.dao;

 

import com.kfs.bean.User;

import org.apache.ibatis.annotations.Mapper;

import tk.mybatis.mapper.common.MySqlMapper;

 

@Mapper //必须加,为了让能找到dao层

public interface UserMapper extends tk.mybatis.mapper.common.Mapper<User>, MySqlMapper<User> {//springboot用通用mapper需要实现两个接口(Mapper和MySqlMapper)

 

}

 

6.业务层

UserService接口

package com.kfs.service;

 

import com.kfs.bean.User;

 

import java.util.List;

 

public interface UserService {

    public List<User> selectAll();

}

 

UserServiceImp实现类

package com.kfs.service;

 

import com.kfs.bean.User;

import com.kfs.dao.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import java.util.List;

 

@Service

public class UserServiceImp implements UserService{

    @Autowired

    private UserMapper userMapper;

 

    public List<User> selectAll(){

        return userMapper.selectAll();

    }

}

 

7.控制层

package com.kfs.controller;

 

import com.kfs.bean.User;

import com.kfs.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

 

import java.util.List;

 

@Controller

public class UserController {

    @Autowired

    private UserService userService;

 

    @ResponseBody

    @RequestMapping("testMapper")

    public List<User> testMapper(){

        List<User> users = userService.selectAll();

        return users;

    }

 

}

 

Springboot使用PageHelper

1.导入jar包(添加依赖)

        <!-- 分页插件 -->

        <dependency>

            <groupId>com.github.pagehelper</groupId>

            <artifactId>pagehelper-spring-boot-starter</artifactId>

            <version>1.2.10</version>

        </dependency>

 

2.在service层正常使用

package com.pagehelper.service;

 

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;

import com.pagehelper.bean.User;

import com.pagehelper.dao.UserMapper;

import com.pagehelper.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import java.util.List;

 

@Service

public class UserServiceImp implements UserService {

    @Autowired

    private UserMapper userMapper;

 

    public PageInfo<User> selectAll(){

        PageHelper.startPage(1,2);

        List<User> users = userMapper.selectAll();

        return new PageInfo<>(users);

    }

}

 

 

Springboot的热部署

1.加入jar包

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-devtools</artifactId>

            <optional>true</optional>

            <scope>true</scope>

        </dependency>

 

2.在pom.xml里的bulid里开启热部署

       <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

                <configuration>

                    <fork>true</fork><!--必须添加这个配置-->

                </configuration>

            </plugin>

        </plugins>

    </build>

 

3.IDEA自动编译默认关闭的,需要开启

 

 

 

4.勾上compiler.automake.allow.when.app.running,就可以了,但这样可能会出现问题

 

 

 

 

 

 

5.第二种方式(1步骤的jar包必须加)用以下的(鼠标点击IDEA外)有效果(网页和java代码都是热部署)

 

 

 

 

 

 

 

Springboot控制层返回json数据注解;@RestController:写在类上面,一个类的方法都会返回json数据。@ResponseBody:写在方法上,一个方法会返回json数据。

 

Springboot使用Redis

1.引入依赖

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-redis</artifactId>

        </dependency>

 

2.实体类:必须实现序列化接口,redis封装的方法会用序列化和反序列化

package com.pagehelper.bean;

 

import org.springframework.stereotype.Repository;

 

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

import java.io.Serializable;

 

@Table(name = "tb_user")

public class User implements Serializable{

 

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

 

    private String userName;//通用Mapper可以把驼峰规则的大写字母变成_(下划线)加小写来使用

    private String password;

    private String name;

 

    public User() {

    }

 

    @Override

    public String toString() {

        return "User{" +

                "id=" + id +

                ", userName='" + userName + '\'' +

                ", password='" + password + '\'' +

                ", name='" + name + '\'' +

                '}';

    }

 

    public Long getId() {

        return id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getUserName() {

        return userName;

    }

 

    public void setUserName(String userName) {

        this.userName = userName;

    }

 

    public String getPassword() {

        return password;

    }

 

    public void setPassword(String password) {

        this.password = password;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public User(String userName, String password, String name) {

        this.userName = userName;

        this.password = password;

        this.name = name;

    }

}

 

3.业务层

接口

package com.pagehelper.service;

 

 

import com.github.pagehelper.PageInfo;

import com.pagehelper.bean.User;

 

import java.util.List;

 

public interface UserService {

    public List<User> selectAll();

}

 

接口实现类

package com.pagehelper.service;

 

import com.pagehelper.bean.User;

import com.pagehelper.dao.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.serializer.RedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;

import org.springframework.stereotype.Service;

 

import java.util.List;

 

@Service

public class UserServiceImp implements UserService {

    @Autowired

    private UserMapper userMapper;

    @Autowired

    private RedisTemplate<Object,Object> redisTemplate;

 

 

    /**

     *  并发时数据不安全,加同步代码块,双重锁

     * @return

     */

    @Override

    public List<User> selectAll(){

        //设置key以string方式序列化:不弄key会以其他的方式序列化

        RedisSerializer redisSerializer=new StringRedisSerializer();

        redisTemplate.setKeySerializer(redisSerializer);

        //1.查询redis

        List<User> users=(List<User>)redisTemplate.opsForValue().get("test");

        if(users==null){//双重锁

            synchronized (this){

                users=(List<User>)redisTemplate.opsForValue().get("test");

                if(users==null){

                    users = userMapper.selectAll();

                    redisTemplate.opsForValue().set("test",users);

                    System.out.println("mysql");

                }else {

                    System.out.println("redisin");

                }

            }

        }else {

            System.out.println("redisout");

        }

        return users;

    }

}

 

4.属性文件:application.properties

#配置数据源

spring.datasource.username=root

spring.datasource.password=123

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

 

#单个redis配置

#spring.rabbitmq.host=127.0.0.1

#spring.rabbitmq.port=6379

 

#redis哨兵模式:会自动找master,会自动选master

spring.redis.sentinel.master=mymaster

spring.redis.sentinel.nodes=192.168.1.163:26379

 

 

Springboot使用拦截器

1.创建一个拦截器TestIntceptor

package com.pagehelper.inteceptor;

 

import org.springframework.web.servlet.HandlerInterceptor;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class TestInteceptor implements HandlerInterceptor {

    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("拦截器in");

        return false;

    }

}

 

2.创建一个springboot的配置类

package com.pagehelper.config;

 

import com.pagehelper.inteceptor.TestInteceptor;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration  //<beans></beans>

public class TestConfig extends WebMvcConfigurationSupport {

    @Override

    protected void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new TestInteceptor()).addPathPatterns("/test/test1");

    }

}

 

 

Springboot使用Dubbo+zookeeper

1.zookeeper一定要启动

2.一个有实体类和service接口的api(Maven工程)被依赖需要Maven install

实体类:User

package com.kfs.bean;

 

import java.io.Serializable;

 

/**

 *   dubbo的实体类必须序列化

 * @author KFS

 *

 */

public class User implements Serializable{

 

    /**

     *

     */

    private static final long serialVersionUID = 1L;

 

    private Long id;

    private String name;

    public User() {

        super();

    }

    public User(Long id, String name) {

        super();

        this.id = id;

        this.name = name;

    }

    public Long getId() {

        return id;

    }

    public void setId(Long id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    @Override

    public String toString() {

        return "User [id=" + id + ", name=" + name + "]";

    }

 

 

}

 

service接口:UserService

package com.kfs.service;

 

import java.util.List;

 

import com.kfs.bean.User;

 

public interface UserService {

    public List<User> selectAll();

 

    void test1();

}

 

3.生产者(Springboot工程)

a)      引入Maven依赖(最好引入推荐的,引其他的容易冲突)

<dependency>

            <groupId>com.springboot</groupId>

            <artifactId>springboot-dubbo-api</artifactId>

            <version>1.0-SNAPSHOT</version>

        </dependency>

 

        <dependency>

            <groupId>com.alibaba.boot</groupId>

            <artifactId>dubbo-spring-boot-starter</artifactId>

            <version>0.2.0</version>

        </dependency>

 

        <dependency>

            <groupId>org.apache.zookeeper</groupId>

            <artifactId>zookeeper</artifactId>

            <version>3.4.8</version>

            <exclusions>

                <exclusion>

                    <groupId>org.slf4j</groupId>

                    <artifactId>slf4j-log4j12</artifactId>

                </exclusion>

            </exclusions>

        </dependency>

 

b)      接口的实现类:UserServiceImp,其中@Service是alibaba的jar包中的

package com.kfs.service.imp;

 

import java.util.ArrayList;

import java.util.List;

 

import com.alibaba.dubbo.config.annotation.Service;

import com.kfs.bean.User;

import com.kfs.service.UserService;

@Service(version = "${application.version}")

public class UserServiceImp implements UserService {

 

    @Override

    public List<User> selectAll(){

        List<User> users=new ArrayList<User>();

        users.add(new User(1L,"李一"));

        users.add(new User(2L,"李二"));

        return users;

    }

 

    @Override

    public void test1() {

        // TODO Auto-generated method stub

 

    }

 

}

 

c)      属性配置文件:application.properties

server.port=8001

dubbo.application.name=springboot-dubbo-provider

dubbo.registry.address=zookeeper://127.0.0.1:2181

dubbo.protocol.name=dubbo

dubbo.protocol.port=20880

#dubbo.scan.base-packages=com.kfs.service.imp   ?没用!

 

application.version=1.0.0

 

d)      生产者的启动入口需要加入注解:@EnableDubbo:为了确保springboot去执行zookeeper的配置文件

package com.kfs;

 

import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

 

@SpringBootApplication

@EnableDubbo

public class SpringbootDubboProviderApplication {

 

    public static void main(String[] args) {

        SpringApplication.run(SpringbootDubboProviderApplication.class, args);

    }

 

}

 

4.消费者(Springboot)

a)      引入Maven依赖(最好引入推荐的,引其他的容易冲突)

<dependency>

            <groupId>com.springboot</groupId>

            <artifactId>springboot-dubbo-api</artifactId>

            <version>1.0-SNAPSHOT</version>

        </dependency>

 

        <dependency>

            <groupId>com.alibaba.boot</groupId>

            <artifactId>dubbo-spring-boot-starter</artifactId>

            <version>0.2.0</version>

        </dependency>

 

        <dependency>

            <groupId>org.apache.zookeeper</groupId>

            <artifactId>zookeeper</artifactId>

            <version>3.4.8</version>

            <exclusions>

                <exclusion>

                    <groupId>org.slf4j</groupId>

                    <artifactId>slf4j-log4j12</artifactId>

                </exclusion>

            </exclusions>

        </dependency>

 

b)      控制层测试:UserController,@Reference是alibaba的用来让dubbo消费者注入生产者的类

package com.kfs.controller;

 

import com.alibaba.dubbo.config.annotation.Reference;

import com.kfs.bean.User;

import com.kfs.service.UserService;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

 

import java.util.List;

 

@RestController

public class UserController {

    @Reference(version = "${application.version}")

    private UserService userService;

 

    @RequestMapping("testDubbo")

    public void test(){

        List<User> users = userService.selectAll();

        System.out.println(users);

    }

}

 

c)      属性配置文件:application.properties

server.port=8002

dubbo.application.name=springboot-dubbo-concumer

dubbo.registry.address=zookeeper://127.0.0.1:2181

 

application.version=1.0.0

 

Springboot使用thymeleaf

1.引入依赖

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-thymeleaf</artifactId>

        </dependency>

 

2.在resources下templates下可以创建.html文件,再在头部添加thymeleaf名称空间声明:<html  xmlns:th="http://www.thymeleaf.org">。

<!DOCTYPE html>

<html  xmlns:th="http://www.thymeleaf.org"> <!-- thymeleaf名称空间声明 -->

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

 

</body>

</html>

 

Springboot+Dubbo+PageHelper

  1. 引入依赖
  2. 生产者正常使用PageHelper
  3. 消费者调用时需要配置数据源,可能消费者调用生产者PageHelper方法时,消费者会调用数据源,所以消费者需要配置数据源。也可以在消费者springboot入口处加入(@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}))可以取消对数据源的调用。
posted on 2019-11-16 17:39  kfsrex  阅读(160)  评论(0编辑  收藏  举报