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;
}
}