spring boot 系列之六:深入理解spring boot的自动配置

我们知道,spring boot 自动配置功能可以根据不同情况来决定 spring 配置应该用哪个,不应该用哪个,举个例子:

  • Spring 的 JdbcTemplate 是不是在 Classpath 里面?如果是,并且 DataSource 也存在,就自动配置一个 JdbcTemplate 的 Bean
  • Thymeleaf 是不是在 Classpath 里面?如果是,则自动配置 Thymeleaf 的模板解析器、视图解析器、模板引擎

那个这个是怎么实现的呢?原因就在于它利用了 Spring 的条件化配置,条件化配置允许配置存在于应用中,但是在满足某些特定条件前会忽略这些配置。

要实现条件化配置我们要用到 @Conditional 条件化注解。

本篇随便讲从如下三个方面进行展开:

  1. @Conditional 小例子,来说明条件化配置的实现方式
  2. spring boot 的条件化配置详解
  3. spring boot 自动配置源码分析
  4. 自己动手实现 spring boot starter pom

一、@Conditional 小例子

我们知道在 windows 下显示列表的命令是 dir,而在 linux 系统下显示列表的命令是 ls,基于条件配置,我们可以实现在不同的操作系统下返回不同的值。

  1. 判断条件定义
    1. )windows 下的判定条件
      复制代码
      /**
       * 实现 spring 的 Condition 接口,并且重写 matches() 方法,如果操作系统是 windows 就返回 true
       *
       */
      public class WindowsCondition implements Condition{
      
      @Override
      public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
          
          return context.getEnvironment().getProperty("os.name").contains("Windows");
      }
      

      }

      复制代码
    2. )linux 下的判定条件
      复制代码
      /**
       * 实现 spring 的 Condition 接口,并且重写 matches() 方法,如果操作系统是 linux 就返回 true
       *
       */
      public class LinuxCondition implements Condition{
      
      @Override
      public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
          
          return context.getEnvironment().getProperty("os.name").contains("Linux");
      }
      

      }

      复制代码
  2. 不同系统下的 Bean 的类
    1. )接口
      public interface ListService {
      
      public String showListLine();
      

      }

    2. )windows 下的 Bean 类
      复制代码
      public class WindowsListService implements ListService{
      
      @Override
      public String showListLine() {
          return "dir";
      }
      

      }

      复制代码
    3. )linux 下的 Bean 的类
      复制代码
      public class LinuxListService implements ListService{
      
      @Override
      public String showListLine() {
          return "ls";
      }
      

      }

      复制代码
  3. 配置类
    复制代码
    @Configuration
    public class ConditionConfig {
    
    /**
     * 通过@Conditional 注解,符合windows条件就返回WindowsListService实例
     * 
     */
    @Bean
    @Conditional(WindowsCondition.class)
    public ListService windonwsListService() {
        return new WindowsListService();
    }
    
    /**
     * 通过@Conditional 注解,符合linux条件就返回LinuxListService实例
     * 
     */
    @Bean
    @Conditional(LinuxCondition.class)
    public ListService linuxListService() {
        return new LinuxListService();
    }
    

    }

    复制代码
  4. 测试类
    复制代码
    public class ConditionTest {
    
    public static void main(String[] args) {
    
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
        ListService listService = context.getBean(ListService.class);
        System.out
                .println(context.getEnvironment().getProperty("os.name") + " 系统下的列表命令为: " + listService.showListLine());
    }
    

    }

    复制代码
  5. 运行测试类,由于我的是 windows7 系统,因此结果是
    Windows 7 系统下的列表命令为: dir

    如果你的是 linux 系统,则结果就会是

    Linux 系统下的列表命令为: ls

二、spring boot 的条件化配置

在 spring boot 项目中会存在一个名为 spring-boot-autoconfigure 的 jar 包

条件化配置就是在这个 jar 里面实现的,它用到了如下的条件化注解,这些注解都是以 @ConditionalOn 开头的,他们都是应用了 @Conditional 的组合注解:

接下来我们看个源码的列子:

以 JdbcTemplateAutoConfiguration 为例,它里面有这段代码:

@Bean
    @Primary
    @ConditionalOnMissingBean(JdbcOperations.class)
    public JdbcTemplate jdbcTemplate() {return new JdbcTemplate(this.dataSource);
    }

只有在不存在 JdbcOperations(如果查看 JdbcTemplate 的源码,你会发现 JdbcTemplate 类实现了 JdbcOperations 接口)实例的时候,才会初始化一个 JdbcTemplate 的 Bean。

基于以上内容,我们就可以阅读自动配置相关的源码了。

 

三、spring boot 自动配置源码分析

spring boot 项目的启动类用的注解 --@SpringBootApplication 是一个组合注解,其中 @EnableAutoConfiguration 是自动配置相关的。

而这个 @EnableAutoConfiguration 注解里面有个 @Import 注解导入了 EnableAutoConfigurationImportSelector 用来实现具体的功能

(注:由于我本地的 spring boot 版本不是最新的,这里的 EnableAutoConfigurationImportSelector 已经不建议使用了,新版本可能已经换成了其他类,但是不影响我们看代码)

 这个类继承了 AutoConfigurationImportSelector

进入父类,里面有个方法 selectImports()调用了方法 getCandidateConfigurations(),进而调用了 SpringFactoriesLoader.loadFactoryNames()方法

在 SpringFactoriesLoader.loadFactoryNames()方法里面,我们看到会查询 META-INF/spring.factories 这个配置文件

SpringFactoriesLoader.loadFactoryNames 方法会扫描具有 META-INF/spring.factories 文件的 jar 包,而我们的 spring-boot-autoconfigure.jar 里面就有一个这样的文件,此文件中声明了具体有哪些自动配置:

我们上面提到的 JdbcTemplateAutoConfiguration 自动配置类就在里面。

 四、编写自己的 spring boot starter pom

接下来,我们就来写一个简单的 spring boot starter pom。

步骤如下:

  1. 新建 starter maven 项目 spring-boot-starter-hello
  2. 修改 pom 文件
    复制代码
    <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>
        <groupId>com.sam</groupId>
        <artifactId>spring-boot-starter-hello</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
    &lt;dependencies&gt;
        &lt;!-- 这里需要引入spring boot的自动配置作为依赖 --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-autoconfigure&lt;/artifactId&gt;
            &lt;version&gt;1.5.1.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
    
    
    &lt;/dependencies&gt;
    

    </project>

    复制代码
  3. 属性配置
    复制代码
    /**
     * @ConfigurationProperties
     * 自动匹配 application.properties 文件中 hello.msg 的值,然后赋值给类属性 msg,这里的 msg 默认值为“spring boot”
     *
     */
    @ConfigurationProperties(prefix="hello")
    public class HelloServiceProperties {
    
    private static final String MSG = "spring boot";
    
    private String msg = MSG;
    
    public String getMsg() {
        return msg;
    }
    
    public void setMsg(String msg) {
        this.msg = msg;
    }
    

    }

    复制代码
  4. 判定依据类
    复制代码
    /**
     * 后面的代码会依据此类是否存在,来决定是否生产对应的 Bean
     *
     */
    public class HelloService {
    
    private String msg;
    
    public String getMsg() {
        return msg;
    }
    
    public void setMsg(String msg) {
        this.msg = msg;
    }
    
    public String sayHello() {
        return "hello " + msg;
    }
    

    }

    复制代码
  5. 自动配置类
    复制代码
    @Configuration
    @EnableConfigurationProperties(HelloServiceProperties.class)
    @ConditionalOnClass(HelloService.class)
    @ConditionalOnProperty(prefix = "hello", matchIfMissing = true, value = "enabled")
    public class HelloServiceAutoConfiguration {
    
    @Autowired
    HelloServiceProperties helloServiceProperties;
    
    @Bean
    @ConditionalOnMissingBean(HelloService.class)
    public HelloService helloService() {
        HelloService service = new HelloService();
        service.setMsg(helloServiceProperties.getMsg());
        return service;
    }
    

    }

    复制代码

    根据 HelloServiceProperties 提供的参数,并通过 @ConditionalOnClass(HelloService.class) 判定 HelloService 这个类在 Classpath 中是否存在,存在并且还没有对应的 Bean,就生成对应的 helloService Bean

  6. 注册配置,需要到 META-INF/spring.factories 文件中注册改自动配置类:在 src/main/source 目录下新建改文件,然后进行配置。
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    com.sam.spring_boot_starter_hello.HelloServiceAutoConfiguration
  7. 对该工程进行 mvn clean install,将 jar 推送到本地 maven 仓库,供后续使用。
  8. 使用 starter ,使用我们这个 starter 需要新建一个或使用既存的一个 spring boot 工程(这里我用的是既存的),然后
    1. )修改 pom,引入上述的依赖
      <dependency>
                  <groupId>com.sam</groupId>
                  <artifactId>spring-boot-starter-hello</artifactId>
                  <version>0.0.1-SNAPSHOT</version>
              </dependency>
    2. )实现 controller
      复制代码
      @RestController
      public class HelloController {
        // 代码中没有配置这个 helloService Bean,但是自动配置能够帮忙实例化,因此可以直接注入
          @Autowired
          HelloService helloService;
      
      @RequestMapping(value="/helloService")
      public String sayHello() {
          return helloService.sayHello();
      }
      

      }

      复制代码
    3. )页面访问 /helloService 接口

       

    4. )在 application.properties 里面配置 hello.msg=sam,然后再次访问 /helloService 接口