Spring配置类-使用ConfigurationProperties 动态获取配置文件信息
使用场景: 有时候需要再配置类Configuration中动态获取配置文件properties中的自定义值
原始方法:使用ClassLoader读取
缺点: 该方式只能读取类路径下的配置文件
**案例:**创建一个自定义参数的线程池,参数从配置文件中获取
@Configuration
public class MyThreadConfig {
@Bean
public ThreadPoolExecutor threadPool(){
Properties properties = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = MyThreadConfig.class.getClassLoader().getResourceAsStream("config.properties");
// 使用properties对象加载输入流
try {
properties.load(in);
return new ThreadPoolExecutor(new Integer(properties.getProperty("coreSize")),
new Integer(properties.getProperty("maxSize")),
new Long(properties.getProperty("keepAliveTime")),
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(100000),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
使用ConfigurationProperties
导入辅助依赖
这个依赖会只会产生编码时提示,不导入也可以
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
编写配置参数类ThreadPoolConfigPorperties
- 使用@ConfigurationProperties绑定application.properties中的自定义配置
- prefix 前缀定义了哪些外部属性将绑定到类的字段
- @Component 将对象添加进spring容器,方便Config类使用
- 类的字段必须有公共 setter 方法
//绑定配置文件中与gulimail.thread 有关的配置
@ConfigurationProperties(prefix ="gulimail.thread" )
@Component
@Data
public class ThreadPoolConfigProperties {
private Integer coreSize;
private Integer maxSize;
private Integer keepAliveTime;
}
编写配置类MyThreadConfig
- 使用ThreadPoolConfigProperties 作为方法参数,Spring会自动依赖注入对象
- 调用get方法取值
@Configuration
public class MyThreadConfig {
@Bean
public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties properties){
return new ThreadPoolExecutor(properties.getCoreSize(),
properties.getMaxSize(),
properties.getKeepAliveTime(),
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(100000),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
}
}