springboot自定义starter(三)

本文介绍了如何创建并发布自定义的Spring Boot Starter。遵循非官方starter的命名规范,引入必要的依赖,创建AutoConfiguration配置类,配置spring.factories文件,并可选地创建属性提示文件,最后通过Maven发布到仓库,以便于其他项目引用和使用。
摘要由CSDN通过智能技术生成

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依赖就可以使用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值