springboot的starter基于其自动配置实现的,上一篇介绍了springboot自动配置原理。 现在我们自己封装starter发布到maven服务器以达到全局共用的目的。
第一步 引入依赖
starter命名规范:spring官方提供的starter是spring-boot-starter-xx格式的,非官方的starter建议采用xx–spring-boot-starter命名格式。因为spring-boot-starter内部已经整合了spring-boot-autoconfigure所以这里直接引入spring-boot-starter依赖就行了。
第二步 创建AutoConfiguration自动配置类
首先创建一个配置属性映射类
创建自动配置类ThreadPoolExecutorAutoConfiguration
@Configuration
@ConditionalOnClass(value = {ThreadPoolExecutor.class})
@ConditionalOnProperty(prefix = "thread.pool.executor", name = "isOpen", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(value = ThreadPoolExecutorProperties.class)
public class ThreadPoolExecutorAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ThreadPoolExecutor threadPoolExecutor(ThreadPoolExecutorProperties properties) {
System.out.println("核心线程数" + properties.getCorePoolSize());
System.out.println("最大线程数" + properties.getMaxPoolSize());
return new ThreadPoolExecutor(properties.getCorePoolSize(), properties.getMaxPoolSize(), 10, TimeUnit.MINUTES, new LinkedBlockingQueue<>(1000));
}
}
第三步 spring.factories配置文件添加配置类
首先在项目resources文件夹下面创建META-INF文件夹,然后把上面的配置类配置到META-INF/spring.fatories配置文件中。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.djy.threadspringbootstarter.ThreadPoolExecutorAutoConfiguration
第四步 创建属性提示文件(可选)
创建spring-configuration-metadata.json,这个是属性提示文件,在编写yml属性时候可以给出友好提示。
{"properties": [
{
"name": "thread.pool.executor.corePoolSize",
"type": "java.lang.Integer",
"defaultValue": 5,
"description": "线程池核心线程数."
},
{
"name": "thread.pool.executor.maxPoolSize",
"type": "java.lang.Integer",
"defaultValue": 10,
"description": "线程池最大线程数."
}
]}
大功告成,下面就可以maven发布到仓库中,然后在其他项目中引入starter依赖就可以使用了。