Spring Boot Starters到底怎么回事?

前言

上周看了一篇。你一直在用的Spring Boot Starters究竟是怎么回事(https://www.cnblogs.com/fengzheng/p/10947585.html)
 
感觉终于把所有知识都串在一起了,可能还有些地方比较朦胧,但真相感觉就在眼前,只是随时时间的推移罢了。

Starters

开始之前,我们要理解一下 spring boot starter 是什么呢?
 
实际上 starter 并不会包含多少功能代码,我们可以把它理解成一个「连接包」,按照这个概念来说:
它首先是一个包,一个集合,它把需要用的其他功能组件囊括进来,放到自己的 pom 文件中。
然后它是一个连接,把它引入的组件和我们的项目做一个连接,并且在中间帮我们省去复杂的配置,力图做到使用最简单。
 
比如mybatis-spring-boot-starter,他就是对mybatis的一个封装
druid-spring-boot-starter,就是对druid的一个封装

Starters的原理

命名:

也就是我们使用它的时候在 pom 中引用的 artifactId。命名有有规则的,官方规定:
官方的 starter 的命名格式为 spring-boot-starter-{name} ,例如上面提到的 spring-boot-starter-actuator。
非官方的 starter 的命名格式为 {name}-spring-boot-starter

Spring.factories

在 resource/META-INF 目录下创建名称为 spring.factories 的文件,为什么在这里?当 Spring Boot 启动的时候,会在 classpath 下寻找所有名称为 spring.factories 的文件,然后运行里面的配置指定的自动加载类,将指定类(一个或多个)中的相关 bean 初始化。
例如本例中的配置信息是这样的:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.springcloud.boot.starter.example.RedisAutoConfigure
等号前面是固定的写法,后面就是我们自定义的自动配置类了,如果有多个的话,用英文逗号分隔开。
 1 public class RedisAutoConfiguration {
 2  
 3     @Bean
 4     @ConditionalOnMissingBean(name = "redisTemplate")
 5     public RedisTemplate<Object, Object> redisTemplate(
 6             RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
 7         RedisTemplate<Object, Object> template = new RedisTemplate<>();
 8         template.setConnectionFactory(redisConnectionFactory);
 9         return template;
10     }
11 }
 

RedisProperties

1 @ConfigurationProperties(prefix = "spring.redis")
2 public class RedisProperties {
3  
4     private int database = 0;
5  
6     private String url;
7  
8     private String host = "localhost";
9 }
 
 
从这里,知识点基本一下子就串起来了。
  • spring.factories里面配置xxxAutoConfigure。利用了Java的SPI,项目一启动就把configure加载进来。
  • RedisAutoConfiguration里面注入了RedisTemplate的bean。这个bean是对Reids一些常用的操作进行封装。(这里注意一下condition的用法)
  • 最后编写RedisProperties把常用的信息封装一个,可以在properties文件里面配置,非常的方便。
 
posted @ 2019-11-26 20:31  程序员博博  阅读(296)  评论(0编辑  收藏  举报