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()