用过springboot的童鞋们,一定都有过这种经历,需要引入某模块,只需要引入对应的start依赖并配置相应的配置,就可以使用其提供的服务。
下面我们来说说如何实现一个自己的Starter,实现自动autoconfigure
新建一个项目:http-spring-boot-autoconfigure
加入以下依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
示例是自动注入http服务
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>


@ConditionalOnClass // 此注解表示:当spring容器存在此类时则实例化当前bean
最后在resource目录下新建META-INF/spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xxx.http.spring.boot.autoconfigure.HttpServiceAutoConfigure
打包构建后,在需要的项目中引入依赖就可以像在正常使用bean一样直接注入OkHttpClient 。
其实能够实现spring容器帮我们管理自定义Starter里的类,关键是spring.factories里的配置
在spring容器启动的时候会去注入容器默认自动注入的类;具体是在容器refresh的时候会调用ConfigurationClassParser.invokeBeanFactoryPostProcessors

spring 默认提供的配置类

上面的例子是一个不需要配置,下面说一个需要配置的


@ConfigurationProperties("sequence")
@Data
public class SequenceProperties {
private Long datacenterId;
private Long machineId;
}
ConfigurationProperties 注解是将配置文件转换为bean
发现多了一个注解EnableConfigurationProperties ,都是配合ConfigurationProperties使用,此注解作用是在spring容器中找到了能将配置文件转换为bean的bean时生效
所以在注入ISequenceService时,我们需要在配置文件中添加对应的配置否则ISequenceService是没有托管给容器的,也就获取不到实例了
