1、配置屬性的提示工具,導入相對應的依賴,
<!--配置屬性的提示工具-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、創建一個類用於屬性映射
@Data @Component //放入bean中,該服務下任何位置都可以使用 @ConfigurationProperties(prefix = "myproject.thread") //自定義標識前綴 public class ThreadPoolConfigProperties { private Integer coreSize; private Integer maxSize; private Integer keepAliveTime; }
3、編寫線程池配置類
//@EnableConfigurationProperties(ThreadPoolConfigProperties.class)
//開啟ThreadPoolConfigProperties類的屬性配置,注入后可以獲取到該類了。如果該類已經在容器中了,就不需要再寫該注解,直接使用即可 @Configuration public class MyThreadConfig { @Bean public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties threadPoolConfigProperties) { return new ThreadPoolExecutor( threadPoolConfigProperties.getCoreSize(), threadPoolConfigProperties.getMaxSize(), threadPoolConfigProperties.getKeepAliveTime(), TimeUnit.SECONDS, new LinkedBlockingQueue(100), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } }
4、application.properties文件中定義
# 自定義的線程池的配置 myproject.thread.core-size=20 myproject.thread.max-size=100 myproject.thread.keep-alive-time=10
幾個注解:
@Component //將該類放入bean中,該微服務下任何位置都可以使用
@ConfigurationProperties(prefix = "gulimall.thread") //配合屬性,自定義標識前綴
@EnableConfigurationProperties(ThreadPoolConfigProperties.class) //開啟配置屬性,並指定屬性類