springboot @ConfigurationProperties自定义绑定配置

1、如果你写了一个配置,想让配置里边的参数直接通过yml来进行配置,这就需要使用到@ConfigurationProperties来实现。

@Configuration
public class myThreadConfig {
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
      return  new ThreadPoolExecutor(
                20,
                200,
                10,TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

    }
}

比如这个线程池,我想把里边的核心线程数(core-size)、最大线程数(max-size)、存活时间(keep-alive-time)抽取出来直接在yml里边配置。

实现步骤:

直接将需要在yml配置的参数抽取出来成一个组件,然后使用@ConfigurationProperties来进行属性绑定即可。

@ConfigurationProperties(prefix = "jdmall.thread")
@Component
@Data
public class ThreadPoolConfigProperties {
    //核心线程数
    private Integer coreSize;
    //最大线程数
    private Integer maxSize;
    //线程存活时间
    private Integer keepAliveTime;
}

然后在yml(或者properties)里来配置自己自定义的组件:
在这里插入图片描述

最终在原来的配置中使用@EnableConfigurationProperties()来启用即可
像下边这样

@EnableConfigurationProperties(ThreadPoolConfigProperties.class)
@Configuration
public class myThreadConfig {
    @Autowired
    ThreadPoolConfigProperties pool;
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
      return  new ThreadPoolExecutor(
              pool.getCoreSize(),
                pool.getMaxSize(),
                pool.getKeepAliveTime(),TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

    }
}

在使用 @Autowired将抽取的组件注入进来

 @Autowired
 ThreadPoolConfigProperties pool;

最终替换参数:

pool.getCoreSize(),
pool.getMaxSize(),
pool.getKeepAliveTime()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值