目录
springboot的使用是如此的方便,引入一个响应的starter加上少许的配置,就能使用响应的功能了,那这些starter都是怎么实现的呢?
不会写没有关系,但是作为程序员,我们要会复制粘贴。
源码分析
spring.factories
在spring-boot-autoconfigure包下,在META-INF下找到spring.factories文件,内容如下:
我们就以RedisAutoConfiguration为例,看看官方是怎么做的。
RedisAutoConfiguration
1.先看类名
这上有三个注解:@Configuration,@ConditionalOnClass,@EnableConfigurationProperties
他们的作用分别是什么呢?
@Configuration:告诉springboot,这是一个配置类,可以供spring加载
@ConditionalOnClass:这是一个条件注入类,告诉spring,在classpath路径下存在某些类的时候,加载这个配置类。
类似的注解还有很多,idea中搜索下,会发现有这么多:
@EnableConfigurationProperties:引入我们的配置文件类,告诉springboot,这个是我们的参数配置类
我们点击RedisProperties跟踪进去,会发现其类上还有一个注解:
这个其实就是我们在yaml配置的属性信息隐射用的注解了。
ok,到目前为止,RedisAutoConfiguration类上的注解就看完了。
接下来,看看RedisAutoConfiguration类里的内容吧!
我们就看两个具有代表性的东东吧,上图:
是不是和我们平时按条件注册自定义bean是一样的?!
ok,以上只是我们coding的注入,配置等插件信息,那怎么样才能让我们自定义的AutoConfiguration让springboot发现呢?
答案其实就是文章的开头内容。
只要我们在我们定义的classpath下的META-INF目录下,创建一个spring.factories文件,在里面加上:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
xxx.xxx.xxxx.XXXAutoConfiguration
这样,我们自定义的start就可以使用了。
补充以下两点:
一:命名方式
一般我们自定义的start的命名方式,采用xxx-spring-boot-starter的方法进行命名,就像mybatis-spring-boot-starter一样,表示这是第三方写的插件,而不是spring官方提供的方式。
二:project组织形式
一般我们采用两个项目来写我们自己的starter:
- 启动器模块
- 自动配置模块
启动器模块
启动器模块中,我们只要定义我们的pom坐标和引入我们自动配置的模块即可,例如:
<!‐‐启动器‐‐>
<groupId>com.xxx.starter</groupId>
<artifactId>xxx‐spring‐boot‐starter</artifactId>
<version>1.0‐SNAPSHOT</version>
<dependencies>
<!‐‐引入自动配置模块‐‐>
<dependency>
<groupId>com.xxx.starter</groupId>
<artifactId>xxx‐spring‐boot‐starter‐autoconfigurer</artifactId>
<version>0.0.1‐SNAPSHOT</version>
</dependency>
</dependencies>
总结起来就两个:pom坐标名称,引入配置模块
自动配置模块
自动配置模块相比启动器,引入的东西就要多一点了:
- 定义pom(和启动器引入的模块一致)
- 继承springboot的parent,选择合适的版本
- 引入spring-boot-starter:所有starter的基本配置
- 引入自定义配置依赖的pom
直接上代码举例吧:
<modelVersion>4.0.0</modelVersion>
<groupId>com.xxx.starter</groupId>
<artifactId>xxx‐spring‐boot‐starter‐autoconfigurer</artifactId>
<version>0.0.1‐SNAPSHOT</version>
<packaging>jar</packaging>
<name>xxx‐spring‐boot‐starter‐autoconfigurer</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!‐‐ lookup parent from repository ‐‐>
</parent>
<properties>
<project.build.sourceEncoding>UTF‐8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF‐8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!‐‐引入spring‐boot‐starter;所有starter的基本配置‐‐>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter</artifactId>
</dependency>
</dependencies>