SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor

本文介绍了如何在SpringBoot项目中使用自动配置功能开启代码提示,并创建一个线程池配置类ThreadPoolConfigProperties,以及如何在properties文件中配置线程池参数,并在MyThreadConfig中引用自动配置实现线程池管理。
摘要由CSDN通过智能技术生成

1、引入自动配置依赖开启代码提示功能

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

2、编写一个自动配置类

@ConfigurationProperties(prefix = "gulimall.thread")
@Component
@Data
public class ThreadPoolConfigProperties {
    private Integer corePoolSize;
    private Integer maxPoolSize;
    private Integer keepAliveTime;
}

3、在properties中加入常量配置

# 线程池的参数
gulimall.thread.core-pool-size=20
gulimall.thread.max-pool-size=200
gulimall.thread.keep-alive-time=10

4、引用自动配置

​ 因为自动配置类中使用了Componet注解所以可以直接在SpringBoot容器中的方法的参数中直接引入

​ 如果没有加入Component则需要在引入的地方加入@EnableConfigurationProperties(ThreadPoolConfigProperties.class),然后使用Auto注入使用

@Configuration
public class MyThreadConfig {
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties threadPoolConfigProperties) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                threadPoolConfigProperties.getCorePoolSize(), // 核心线程数
                threadPoolConfigProperties.getMaxPoolSize(), // 最大线程数
                threadPoolConfigProperties.getKeepAliveTime(), // 线程空闲后的最大存活时间
                TimeUnit.SECONDS, // 时间单位
                new LinkedBlockingDeque<>(20000), // 任务队列
                new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
        );
        return executor;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值