Spring Boot概述与入门&特点&配置方式&注入方式&yim配置文件与多文件配置&Spring Boot自动配置原理&lombok应用

1. Spring Boot概述

Spring Boot是Spring项目中的一个子工程,与我们所熟知的Spring-framework 同属于spring的产品:
在这里插入图片描述首页Spring Boot简介可以看到下面的一段介绍:

一般把Spring Boot称为搭建程序的 脚手架 或者说是便捷搭建 基于Spring的工程 脚手架。其最主要作用就是帮助开
发人员快速的构建庞大的spring项目,并且尽可能的减少一切xml配置,做到开箱即用,迅速上手,让开发人员关注业务而非配置。

学习目标:了解Spring Boot是什么,有什么作用

总结

Spring Boot是一个便捷搭建 基于spring工程的脚手架;作用是帮助开发人员快速搭建大型的spring 项目。简化工程的配置,依赖管理;实现开发人员把时间都集中在业务开发上。

2. Spring Boot入门

java一直被人诟病的一点就是臃肿、麻烦。当我们还在辛苦的搭建项目时,可能Python程序员已经把功能写好了,

究其原因注意是两点:

  • 复杂的配置

    项目各种配置其实是开发时的损耗, 因为在思考 Spring 特性配置和解决业务问题之间需要进行思维切换,所以写配置挤占了写应用程序逻辑的时间。

  • 一个是混乱的依赖管理

    项目的依赖管理也是件吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪个版本和其他库不会有冲突,这难题实在太棘手。并且,依赖管理也是一种损耗,添加依赖不是写应用程序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。

而Spring Boot让这一切成为过去!

Spring Boot 简化了基于Spring的应用开发,只需要“run”就能创建一个独立的、生产级别的Spring应用。
Spring Boot为Spring平台及第三方库提供开箱即用的设置(提供默认设置,存放默认配置的包就是启动器starter),这样我们就可以简单的开始。多数Spring Boot应用只需要很少的Spring配置。

我们可以使用Spring Boot创建java应用,并使用java –jar 启动它,就能得到一个生产级别的web工程。

学习目标:能够使用Spring Boot搭建项目

解析

需求:可以在浏览器中访问http://localhost:8080/hello输出一串字符

实现步骤:

  1. 创建工程;

  2. 添加依赖(启动器依赖,spring-boot-starter-web);
    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.5.RELEASE</version>
        </parent>
        <groupId>com.heiheihei</groupId>
        <artifactId>heiheiheispringboot</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    </project>
    
  3. 创建启动类;

    package com.heiheihei;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/28 20:56
     */
    
    /**
     * spring boot工程都有一个启动引导类,这是工程的人口类
     * 并在引导类上添加@SpringBootApplication
     */
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }
    
  4. 创建处理器Controller;

    package com.heiheihei.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/28 21:07
     */
    @RestController
    public class HelloController {
    
    
        @GetMapping("hello")
        public String hello() {
            return "hello, Spring Boot!";
        }
    }
    
  5. 测试
    在这里插入图片描述
    总结

    Spring Boot工程可以通过添加启动器依赖和创建启动引导类实现快速创建web工程。

    spring-boot-starter-web默认的应用服务器端口是8080

2.1 Spring Boot的特点

Spring Boot 主要特点是:

  • 创建独立的Spring应用,为所有 Spring 的开发者提供一个非常快速的、广泛接受的入门体验
  • 直接嵌入应用服务器,如tomcat、jetty、undertow等;不需要去部署war包
  • 提供固定的启动器依赖去简化组件配置;实现开箱即用(启动器starter-其实就是Spring Boot提供的一个jar包),通过自己设置参数(.properties或.yml的配置文件),即可快速使用。
  • 自动地配置Spring和其它有需要的第三方依赖
  • 提供了一些大型项目中常见的非功能性特性,如内嵌服务器、安全、指标,健康检测、外部化配置等
  • 绝对没有代码生成,也无需 XML 配置。

更多细节,大家可以到官网查看。

3. Java代码方式配置

学习目标:可以使用@Value获取配置文件配置项并结合@Bean注册组件到Spring

解析

需求:使用Java代码配置数据库连接池,并可以在处理器中注入并使用

步骤:

  1. 添加依赖

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.6</version>
    </dependency>
    
  2. 创建数据库;

  3. 创建数据库连接参数的配置文件jdbc.properties

    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1:3306/springboot_test
    jdbc.username=root
    jdbc.password=root
    
  4. 创建配置类

    package com.heiheihei.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    import javax.sql.DataSource;
    
    @Configuration
    @PropertySource("classpath:jdbc.properties")
    public class JdbcConfig {
    
        @Value("${jdbc.url}")
        String url;
        @Value("${jdbc.driverClassName}")
        String driverClassName;
        @Value("${jdbc.username}")
        String username;
        @Value("${jdbc.password}")
        String password;
    
        @Bean //注入IOC容器中时默认id为方法名
        public DataSource dataSource(){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    
    }
    
  5. 改造处理器类注入数据源并使用

    package com.heiheihei.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.sql.DataSource;
    
    /**
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/28 21:07
     */
    @RestController
    public class HelloController {
    
        @Autowired
        private DataSource dataSource;
    
        @GetMapping("hello")
        public String hello() {
            System.out.println("dataSource = " + dataSource);
            return "hello, Spring Boot!";
        }
    }
    

总结

使用@Configuration标识配置类,使用@PropertySource(“classpath:jdbc.properties”)进行引入文件,使用@Value进行注入.使用@Bean将方法返回值注入Spring容器.

4. Spring Boot属性注入方式

学习目标:能够使用@ConfigurationProperties实现Spring Boot配置文件配置项读取和应用

解析

需求:将配置文件中的配置项读取到一个对象中;

实现:可以使用Spring Boot提供的注解@ConfigurationProperties,该注解可以将Spring Boot的配置文件(默认必须为application.properties或application.yml)中的配置项读取到一个对象中。

实现步骤:

  1. 创建配置项类JdbcProperties类,在该类名上面添加@ConfigurationProperties

    package com.heiheihei.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    /**
     * ConfigurationProperties从application配置文件中读取配置项
     * prefix表示配置的前缀
     * 配置选类中的类变量必须要与前缀之后的配置项名称保持 松散绑定(相同)
     */
    @ConfigurationProperties(prefix = "jdbc")
    public class JdbcProperties {
        private String url;
        private String driverClassName;
        private String username;
        private String password;
    
       	//生成get和set方法
    }
    
  2. 将jdbc.properties修改名称为application.properties;

  3. 将JdbcProperties对象注入到JdbcConfig;

    方式一

    /**
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/28 21:44
     */
    @Configuration
    @EnableConfigurationProperties(JdbcProperties.class)
    public class JdbcConfig {
    
    
        /**
         * 在可能需要多个Bean使用,使用该方式,并在类上添加@EnableConfigurationProperties(JdbcProperties.class)进行注入
         *
         * @param jdbcProperties
         * @return
         */
        @Bean
        public DataSource dataSource(JdbcProperties jdbcProperties) {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
            dataSource.setUrl(jdbcProperties.getUrl());
            dataSource.setUsername(jdbcProperties.getUsername());
            dataSource.setPassword(jdbcProperties.getPassword());
            return dataSource;
        }
    }
    

    注意:该方法需要配置项类和在注入的类中添加@EnableConfigurationProperties(JdbcProperties.class)注解,并且需要在pom.xml中添加<artifactId>spring-boot-configuration-processor</artifactId>

    方式二(无需配置项类JdbcProperties),Spring Boot默认注入了application.properties

    /**
     * 如果一段属性只有一个Bean需要使用,我们无需将其注入到一个类(JdbcProperties,将该类上的所有注
     * 解去掉)中。而是直接在需要的地方声明即可
     *
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        return new DruidDataSource();
    }
    

    注意:我们直接把@ConfigurationProperties(prefix = "jdbc")声明在需要使用的 @Bean 的方法上,然后Spring Boot就会自动调用这个Bean(此处是DataSource)的set方法,然后完成注入。使用的前提是:该类必须有对应属性的set方法!

  4. 测试

总结

  • 第一种:使用@ConfigurationProperties编写配置项类将配置文件中的配置项设置到对象中

    @ConfigurationProperties(prefix = "jdbc")
    public class JdbcProperties {
    
        private String url;
        private String driverClassName;
        private String username;
        private String password;
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public String getDriverClassName() {
            return driverClassName;
        }
    
        public void setDriverClassName(String driverClassName) {
            this.driverClassName = driverClassName;
        }
    
        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;
        }
    }
    
    

    并在在pom.xml中添加坐标<artifactId>spring-boot-configuration-processor</artifactId>,再在需要使用引入的值的类中进行添加@EnableConfigurationProperties(JdbcProperties.class)

    @Bean
    public DataSource dataSource(JdbcProperties jdbcProperties) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
        dataSource.setUrl(jdbcProperties.getUrl());
        dataSource.setUsername(jdbcProperties.getUsername());
        dataSource.setPassword(jdbcProperties.getPassword());
        return dataSource;
    }
    

    使用形参进行获取被设置的对象(实际上是根据类类型从SpringIOC容器获取的)

  • 使用@ConfigurationProperties在方法上面使用,无需编写配置项类,但是properties文件名为application.properties,Spring Boot 默认注入了application.properties文件

    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        return new DruidDataSource();
    }
    

    prefix为匹配文件中的前缀,如jdbc.url,然后url匹配需要注入的setUrl()方法

注意:@ConfigurationProperties类似于依赖注入Set方式进行对类(变量的set方法)或方法(根据返回类型的对象变量)进行注入数据(读取appliation.ylm或propertis文件到对象中)

5. 多个yml文件配置

5.1 Yaml配置文件

配置文件除了可以使用application.properties类型,还可以使用后缀名为:.yml或者.yaml的类型,也就是:application.yml或者application.yaml

正如TAML所表示的YAML Ain’t Markup Language, YAML是一个简洁的非标记语言.YAML以数据为中心,使用空白缩进,分行组织数据,从而使得表示更加简洁易读.

学习目标:可以将多个yml文件在application.yml文件中配置激活

解析

yaml与properties配置文件除了展示形式不相同以外,其它功能和作用都是一样的;在项目中原路的读取方式不需要改变。

  1. yml配置文件的特征:

    1. 树状层级结构展示配置项;
    2. 配置项之间如果有关系的话需要分行空两格;
    3. 配置项如果有值的话,那么需要在 :之后空一格再写配置项值;

    将application.properties配置文件修改为application.yml的话:

    如果两个配置文件都有,会把两个文件的配置合并,如果有重复属性,以properties中的为准。

    jdbc:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/heiheihei
      username: root
      password: root
    
    
    key:
      abc: cba
      def:
        - g
        - h
        - j
    

    这里有两组无关系配置项

    如果是配置数组、list、set等结构的内容,那么在yml文件中格式为:

    key:
      - value1
      - value2
    
  2. 多个yml配置文件;在spring boot中是被允许的。这些配置文件的名称必须为application-***.yml ,并且这些配置文件必须要在application.yml配置文件中激活之后才可以使用

    • 在多个配置文件时,需要将这些文件在application.yml文件中进行激活:

      #激活配置文件;需要指定其它的配置文件名称
      spring:
        profiles:
          active: abc,def
      

      多个文件名只需要写application-之后的名称,在多个文件之间使用,隔开。

    • 创建 application-abc.yml 文件如下:

      heiheihei:
      url: http://www.heiheihei.cn
      
    • 创建 application-def.yml 文件如下:

      heiheihei:
      url: http://www.hahaha.com
      
  3. 如果properties和yml配置文件同时存在在spring boot项目中;那么这两类配置文件都有效。在两个配置文件中如果存在同名的配置项的话会以properties文件的为主。

修改代码测试:
在这里插入图片描述结果
在这里插入图片描述

6. 自动配置原理

使用Spring Boot之后,一个整合了SpringMVC的WEB工程开发,变的无比简单,那些繁杂的配置都消失不见了,这是如何做到的?

一切魔力的开始,都是从我们的main函数来的,所以我们再次来看下启动类:
在这里插入图片描述
我们发现特别的地方有两个:

  • 注解:@SpringBootApplication
  • run方法:SpringApplication.run()

由于流程比较复杂,在这不做解释

简化流程描述:

SpringBoot为我们提供了默认配置,而默认配置生效的步骤(重点):

  • @EnableAutoConfiguration注解会去寻找META-INF/spring.factories 文件,读取其中以
    EnableAutoConfiguration 为key的所有类的名称,这些类就是提前写好的自动配置类
  • 这些类都声明了 @Configuration 注解,并且通过 @Bean 注解提前配置了我们所需要的一切实例
  • 但是,这些配置不一定生效,因为有 @ConditionalOn注解,满足一定条件才会生效。
    比如条件之一: 是一些相关的类要存在
  • 类要存在,我们只需要引入了相关依赖(启动器),依赖有了条件成立,自动配置生效。
  • 如果我们自己配置了相关Bean,那么会覆盖默认的自动配置的Bean
  • 我们还可以通过配置application.yml文件,来覆盖自动配置中的属性
  1. 启动器
    所以,我们如果不想配置,只需要引入依赖即可,而依赖版本我们也不用操心,因为只要引入了SpringBoot提供的starter(启动器),就会自动管理依赖及版本了。
    因此,玩SpringBoot的第一件事情,就是找启动器,SpringBoot提供了大量的默认启动器
  2. 全局配置
    另外,SpringBoot的默认配置,都会读取默认属性,而这些属性可以通过自定义 application.properties 文件来进行覆盖。这样虽然使用的还是默认配置,但是配置中的值改成了我们自定义的。
    因此,玩SpringBoot的第二件事情,就是通过 application.properties 来覆盖默认属性值,形成自定义配置。我们需要知道SpringBoot的默认属性key,非常多,可以再idea中自动提示

属性文件支持两种格式,application.propertiesapplication.yml,如果properties和yml文件都存在,如果有重叠属性,默认以Properties优先

学习目标:了解Spring Boot项目的配置加载流程

解析

  • META-INF\spring.factories文件中定义了很多自动配置类;可以根据在pom.xml文件中添加的 启动器依赖自动配置组件
  • 通过如下流程可以去修改application配置文件,改变自动配置的组件默认参数
    在这里插入图片描述

7. lombok应用

我们编写pojo时,经常需要编写构造函数和getter、setter方法,属性多的时候,就非常浪费时间,使用lombok插件可以解决这个问题:

  1. 在IDEA中安装lombok插件;不安装插件在IDEA中使用lombok的注解虽然编译能通过,但是源码会报错。所以为了让IDEA更好的辨别lombok注解则才安装插件。

  2. 需要在maven工程中的 pom.xml 文件引入依赖:

    <dependency>
    	<groupId>org.projectlombok</groupId>
    	<artifactId>lombok</artifactId>
    </dependency>
    

    然后可以在Bean上使用:
    @Data :自动提供getter和setter、hashCode、equals、toString等方法
    @Getter:自动提供getter方法
    @Setter:自动提供setter方法
    @Slf4j:自动在bean中提供log变量,其实用的是slf4j的日志功能。

学习目标:使用lombok的注解实现pojo类的简化

解析

使用Spring Boot整合SSM工程;需要使用到数据库数据。

  • 将数据库表数据导入到数据库中(springboot_test);

  • 编写数据库表对应的实体类;一般情况下需要编写get/set/toString等这些方法会耗时并且会让实体类看起来比较臃肿。可以使用lombok插件对实体类进行简化。

    lombok是一个插件工具类包;提供了一些注解@Data、@Getter等这些注解去简化实体类中的构造方法、get/set等方法的编写。

    1. 在IDEA中安装lombok插件;
      在这里插入图片描述

    2. 添加lombok对应的依赖到项目pom.xml文件;

      <dependency>
      	<groupId>org.projectlombok</groupId>
      	<artifactId>lombok</artifactId>
      </dependency>
      
    3. 改造实体类使用lombok注解

      package com.heiheihei.pojo;
      
      import lombok.Data;
      import lombok.extern.slf4j.Slf4j;
      
      import java.util.Date;
      
      
      /**
       * 用户实体类
       * 在编译阶段根据注解自动生成对应的方法;data包含
       * get/set/hashCode/equals/toString等方法
       * @author 嘿嘿嘿1212
       * @version 1.0
       * @date 2019/10/29 18:37
       */
      @Data
      @Slf4j
      public class User {
      
          private Integer id;
      
          private String userName;
      
          private String password;
      
          private String name;
      
          private Integer age;
      
          private Integer sex;
      
          private Date birthday;
      
          private String note;
      
          private Date created;
      
          private Date updated;
      
      }
      

      引入@Slf4j是为了使用log对象

8. Spring Boot整合-SpringMVC端口和静态资源

虽然默认配置已经可以使用SpringMVC了,不过我们有时候需要进行自定义配置

  • 可以在 application.yml 文件中配置日志级别控制:

    logging:
      level:
        com.heiheihei: debug
        org.springframework: info
    
  • 查看SpringBoot的全局属性可知,端口通过以下方式配置
    修改 application.yml 配置文件,添加如下配置:

    # 映射端口
    server:
      port: 80
    

访问静态资源

现在,我们的项目是一个jar工程,那么就没有webapp,我们的静态资源该放哪里呢?有一个叫做ResourceProperties的类,里面就定义了静态资源的默认查找路径

在spring boot项目中静态资源可以放置在如下目录:

默认的静态资源路径为

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理。

我们习惯会把静态资源放在 classpath:/static/ 目录下。

目标:可以修改tomcat的端口和访问项目中的静态资源

解析

  • 修改tomcat端口

    查询**Properties,设置配置项(前缀+类变量名)到application配置文件中
    在这里插入图片描述
    在这里插入图片描述

    #tomcat端口
    server:
      port: 80
    
  • 访问项目中的静态资源

    静态资源放置的位置;放置静态资源并访问这些资源
    在这里插入图片描述

9.Spring Boot整合-SpringMVC拦截器

拦截器也是我们经常需要使用的,在SpringBoot中该如何配置呢?

拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了。在SpringBoot官方文档中有这么一段说明:
翻译:

如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器,视图控制器、消息转换器 等等),你应该让一个类实现 WebMvcConfigurer ,并且添加 @Configuration 注解,但是千万不要加 @EnableWebMvc 注解。如果你想要自定义 HandlerMappingHandlerAdapterExceptionResolver 等组件,你可以创建一个 WebMvcRegistrationsAdapter 实例 来提供以上组件。如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一切特征,你可以自己定义类并且添加@Configuration 注解和 @EnableWebMvc 注解

总结:通过实现 WebMvcConfigurer 并添加@Configuration 注解来实现自定义部分SpringMvc配置。

目标:可以在Spring Boot项目中配置自定义SpringMVC拦截器

分析

  1. 编写拦截器(实现HandlerInterceptor)
    书写interceptor

    /**
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/29 19:56
     */
    @Slf4j
    public class Myinterceptor implements HandlerInterceptor {
        /**
         * 执行处理器前
         *
         * @param request
         * @param response
         * @param handler
         * @return
         * @throws Exception
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.debug("这是Myinterceptor的preHandle方法");
            return true;
        }
    
        /**
         * 执行处理器之后
         *
         * @param request
         * @param response
         * @param handler
         * @param modelAndView
         * @throws Exception
         */
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            log.debug("这是Myinterceptor的postHandle方法");
        }
    
        /**
         * 渲染页面后
         *
         * @param request
         * @param response
         * @param handler
         * @param ex
         * @throws Exception
         */
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            log.debug("这是Myinterceptor的afterCompletion方法");
        }
    }
    

    可以使用@Component进行注入SpringIOC容器.

  2. 编写配置类实现 WebMvcConfigurer,在该类中添加各种组件;

    配置interceptor

    /**
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/29 20:08
     */
    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
    
        /**
         * 注册拦截器
         *
         * @return
         */
        @Bean
        public Myinterceptor myinterceptor() {
            return new Myinterceptor();
        }
    
        /**
         * 添加拦截器spring MVC的拦截器链
         *
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
        	//注册拦截器,与配置拦截路径
            registry.addInterceptor(myinterceptor()).addPathPatterns("/*");
        }
    }
    

    可以使用@Autowired进行注入

  3. 测试
    在这里插入图片描述

类似于书写interceptor以及配置interceptor

10. Spring Boot整合-事务和连接池

其实,在刚才引入jdbc启动器的时候,SpringBoot已经自动帮我们引入了一个连接池:
在这里插入图片描述
HikariCP应该是目前速度最快的连接池了,我们看看它与c3p0的对比:
在这里插入图片描述
因此,我们只需要指定连接池参数即可;打开 application.yml 添加修改配置如下:

spring:
  datasource:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/springboot_test
      username: root
      password: root

注意:使用默认的连接池需要把配置了其他的连接池的jdbcConfig类内的其他连接池进行注释或删除

学习目标:配置Spring Boot自带默认的hikari数据库连接池和使用@Transactional注解进行事务配置

问题: 事务失效(原因:事务方法嵌套||private方法进行事务管理)动态代理的问题(cglib方式)

解析

  • 事务配置

    1. 添加事务相关的启动器依赖,mysql相关依赖;

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-jdbc</artifactId>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.46</version>
      </dependency>
      
    2. 编写业务类UserService使用事务注解@Transactional

      @Transactional
      public void saveUser(User user) {
          ....
      }
      
  • 数据库连接池hikari配置

    只需要在application配置文件中指定数据库相关参数

    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/springboot_test
        username: root
        password: root
    

总结

  • 事务配置;只需要添加jdbc启动器依赖
  • 数据库连接池使用默认的hikari,在application配置文件中配置如上即可

11. Spring Boot整合-Mybatis

  1. SpringBoot官方并没有提供Mybatis的启动器,不过Mybatis官网自己实现了。在项目的 pom.xml 文件中加入如下依赖:

    <!--mybatis -->
    <dependency>
    	<groupId>org.mybatis.spring.boot</groupId>
    	<artifactId>mybatis-spring-boot-starter</artifactId>
    	<version>2.0.1</version>
    </dependency>
    
  2. 配置 application.yml ,常用配置如下:

    # mybatis配置
    mybatis:
      # 实体类别名包路径
      type-aliases-package: com.heiheihei.pojo
      # 映射文件路径
      #  mapper-locations: classpath:mapper/*.xml
      configuration:
        # 控制台输出执行sql
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
  3. 配置Mapper扫描

    需要注意,这里没有配置mapper接口扫描包,因此我们需要给每一个Mapper接口添加 @Mapper 注解,才能被识别。

    @Mapper
    public interface UserMapper {
    }
    

    或者,我们也可以不加注解,而是在启动类上添加扫描包注解(推荐):

    @SpringBootApplication
    @MapperScan("com.heiheihei.mapper")
    public class Application {
    	public static void main(String[] args) {
    		// 启动代码
    		SpringApplication.run(Application.class, args);
    	}
    }
    

学习目标:配置Mybatis在Spring Boot工程中的整合包,设置mybatis的实体类别名,输出执行sql语句配置项

解析

  1. 添加启动器依赖;
  2. 配置Mybatis:实体类别名包,日志,映射文件等;
  3. 配置MapperScan

12. Spring Boot整合-通用Mapper

  1. 通用Mapper的作者也为自己的插件编写了启动器,我们直接引入即可。在项目的 pom.xml 文件中加入如下依赖:

    <!-- 通用mapper -->
    <dependency>
    	<groupId>tk.mybatis</groupId>
    	<artifactId>mapper-spring-boot-starter</artifactId>
    	<version>2.1.5</version>
    </dependency>
    

    注意:一旦引入了通用Mapper的启动器,会覆盖Mybatis官方启动器的功能,因此需要移除对官方Mybatis启动器的依赖

  2. 编写XXXMapper(XXXDao)
    无需任何配置就可以使用了。如果有特殊需要,可以到通用mapper官网查看:https://github.com/abel533/Mapper/wiki/3.config,但是需要继承Mapper类

    例如:

    package com.heiheihei.mapper;
    import com.heiheihei.pojo.User;
    
    import tk.mybatis.mapper.common.Mapper;
    public interface UserMapper extends Mapper<User> {
    }
    
  3. 把启动类上的@MapperScan注解修改为通用mapper中自带(tk包下)的:
    在这里插入图片描述

  4. 在实体类上加JPA注解

    例如:

    package com.heiheihei.pojo;
    
    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    import tk.mybatis.mapper.annotation.KeySql;
    
    import javax.persistence.Column;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import java.util.Date;
    
    
    /**
     * 用户实体类
     * 在编译阶段根据注解自动生成对应的方法;data包含get/set/hashCode/equals/toString等方法
     *
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/29 18:37
     */
    @Data
    @Table(name = "tb_user")
    public class User {
        @Id
        //开启主键回填
        @KeySql(useGeneratedKeys = true)
        private Integer id;
        //与数据库的字段进行匹配,在表中所有"_" 使用驼峰命名法如user_name-->userName
        //@Column
        private String userName;
    
        private String password;
    
        private String name;
    
        private Integer age;
    
        private Integer sex;
    
        private Date birthday;
    
        private String note;
    
        private Date created;
    
        private Date updated;
    
    }
    
  5. 对 Service 的代码进行简单改造

    /**
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/29 20:35
     */
    @Service
    public class UserService {
        @Autowired
        private UserMapper userMapper;
    
        public User queryById(Integer id) {
           return userMapper.selectByPrimaryKey(id);
        }
    
        @Transactional
        public void saveUser(User user) {
            userMapper.insertSelective(user);
        }
    }
    

    selectByPrimaryKey根据主键查询
    insertSelective选择性插入表 ,未赋值的属性将不进行插入操作.
    selectByPrimaryKey等方法通过动态代理生成

学习目标:配置通用Mapper组件到Spring Boot项目中并使用Mapper接口

解析

通用Mapper:可以实现自动拼接sql语句;所有的mapper都不需要编写任何方法也就是不用编写sql语句。可以提高开发效率。

  1. 添加启动器依赖
  2. 改造XXXMapper继承Mapper<User>
  3. 修改启动引导类Application中的Mapper扫描注解
  4. 修改实体类添加jpa注解
  5. 改造Service实现业务功能

注意要点

在启动引导类上面的mapper扫描注解 一定要修改为 通用mapper的扫描注解

13. Spring Boot整合测试

目标:可以访问处理器对应路径将数据库中的数据根据id查询

分析

  1. 改造HelloController,注入UserService利用其方法实现查询;
  2. 启动项目进行测试 http://localhost/user/用户id --> http://localhost/user/8

小结

修改了HelloController:

    @Autowired
    private UserService userService;

    /**
     * 根据用户id查询用户
     * @param id 用户id
     * @return 用户
     */
    @GetMapping("/user/{id}")
    public User queryById(@PathVariable Long id){
        return userService.queryById(id);
    }

14. Spring Boot整合-Junit

  1. 在springboot项目中如果要使用Junit进行单元测试,则需要添加如下的依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    
  2. 在测试包下编写测试类,使用Ctrl+Shift+T生成测试类,注意勾选测试方法.
    在测试类上面必须要添加 @SpringBootTest 注解。

    例如:

    /**
     * @author 嘿嘿嘿1212
     * @version 1.0
     * @date 2019/10/30 9:53
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UserServiceTest {
    
        @Autowired
        private UserService userService;
    
        @Test
        public void queryById() {
            User user = userService.queryById(8);
            System.out.println("user = " + user);
        }
    
        @Test
        public void saveUser() {
            User user = new User();
            user.setUserName("test2");
            user.setName("魔鬼2号");
            user.setAge(18);
            user.setPassword("10086");
            user.setSex(1);
            user.setCreated(new Date());
            userService.saveUser(user);
        }
    }
    

    测试代码路径结构:
    在这里插入图片描述

学习目标:在Spring Boot项目中使用Junit进行单元测试Service的方法

解析

  1. 添加启动器依赖spring-boot-starter-test
  2. 编写测试类

在Spring Boot项目中如果编写测试类则必须要在类上面添加@SpringBootTest与@RunWith(SpringRunner.class)

15. Spring Boot整合-redis

  1. 在 pom.xml 文件中添加如下依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  2. 配置 application.yml 文件

    spring:
      redis:
        host: localhost
        port: 6379
    

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test(){
        //string 字符串
        //redisTemplate.opsForValue().set("str", "heiheihei");
        redisTemplate.boundValueOps("str").set("heiheihei");
        System.out.println("str = " + redisTemplate.opsForValue().get("str"));

        //hash 散列
        redisTemplate.boundHashOps("h_key").put("name", "heiheihei");
        redisTemplate.boundHashOps("h_key").put("age", 13);
        //获取所有域
        Set set = redisTemplate.boundHashOps("h_key").keys();
        System.out.println(" hash散列的所有域:" + set);
        //获取所有值
        List list = redisTemplate.boundHashOps("h_key").values();
        System.out.println(" hash散列的所有域的值:" + list);

        //list 列表
        redisTemplate.boundListOps("l_key").leftPush("c");
        redisTemplate.boundListOps("l_key").leftPush("b");
        redisTemplate.boundListOps("l_key").leftPush("a");
        //获取全部元素
        list = redisTemplate.boundListOps("l_key").range(0, -1);
        System.out.println(" list列表中的所有元素:" + list);

        // set 集合
        redisTemplate.boundSetOps("s_key").add("a", "b", "c");
        set = redisTemplate.boundSetOps("s_key").members();
        System.out.println(" set集合中的所有元素:" + set);

        // sorted set 有序集合
        redisTemplate.boundZSetOps("z_key").add("a", 30);
        redisTemplate.boundZSetOps("z_key").add("b", 20);
        redisTemplate.boundZSetOps("z_key").add("c", 10);
        set = redisTemplate.boundZSetOps("z_key").range(0, -1);
        System.out.println(" zset有序集合中的所有元素:" + set);
    }
}

学习目标:在Spring Boot项目中使用Junit测试RedisTemplate的使用

解析

  1. 添加启动器依赖;spring-boot-starter-data-redis
  2. 配置application.yml中修改redis的连接参数;(redis需要启动)
  3. 编写测试类应用RedisTemplate操作redis中的5种数据类型(string/hash/list/set/sorted set

16. Spring Boot项目部署

  1. 添加项目的pom.xml插件;在pom.xml要显式的加入插件spring-boot-maven-plugin,否则无法产生 jar 清单文件,导致打出来的 jar 无法使用命令运行

    <build>
      <plugins>
          <plugin>
              <!-- 打jar包时如果不配置该插件,打出来的jar包没有清单文件 -->
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
      </plugins>
    </build>
    
  2. 使用maven的命令package打包;(test比较耗时,无错误的时候可以禁用)
    在这里插入图片描述
    之后在项目下的 target 目录中将有如下jar包:
    在这里插入图片描述

【注意】在查看打出的 jar 的时候,将发现 jar 包里面包含 jar 包;这样的包称为 fatJar(肥包)

  1. 运行

    运行打出来的包:

    • 使用命令:java –jar包全名

    • 或者写一个 bat文件,里面包含 java –jar 包全名,这样就可以双击启动应用。

      如执行上述打出来的jar的命令为:

      java -jar heiheihei-springboot-1.0-SNAPSHOT.jar
      

学习目标:将Spring Boot项目使用maven指令打成jar包并运行测试

解析

  1. 需要添加打包组件将项目中的资源、配置、依赖包打到一个jar包中;可以使用maven的package
  2. 部署:java -jar 包名

补充

在应用spring boot工程的时候;一般情况下都需要创建启动引导类Application.java和application.yml配置文件,而且内容都是一样的;为了便捷可以安装一个IDEA的插件 JBLSpringBootAppGen 在项目上右击之后可以自动生成启动引导类Application.java和application.yml配置文件。

  1. 打开IDEA的设置界面(按 Ctrl+Alt+S )之后在插件选项中搜索SpringBoot,安装 JBLSpringBootAppGen(可能存在热键冲突,无法通过快捷键进入,则File–>Setting–>Plugins)
    在这里插入图片描述 当然需要重启idea
  2. 在IDEA中任意一个maven项目或src目录上 右击,选择 JBLSpringBootAppGen 即可
    在这里插入图片描述点击OK后会自动生成目录与yml文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘿嘿嘿1212

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值