使用版本是1.5.4
举例一个线程池的配置:
在application.yml添加配置项及值
1 2 3 4 5 |
# 线程池配置 taskexecutor: corePoolSize: 5 maxPoolSize: 10 queueCapacity: 25 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Configuration @EnableAsync public class ExecutorConfig { @Value("${taskexecutor.corePoolSize}") private int corePoolSize; @Value("${taskexecutor.maxPoolSize}") private int maxPoolSize; @Value("${taskexecutor.queueCapacity}") private int queueCapacity; @Bean public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("TaskExecutor-"); executor.initialize(); return executor; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@Configuration @EnableAsync @ConfigurationProperties(ignoreUnknownFields = false,prefix = "taskexecutor") public class ExecutorConfig { private int corePoolSize; private int maxPoolSize; private int queueCapacity; @Bean public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("TaskExecutor-"); executor.initialize(); return executor; } } |
通过@ConfigurationProperties加载配置文件,将配置项与bean及属性关联,指定ignoreUnknownFields当有属性未匹配到值时会抛出异常,用prefix指定配置项的前缀。
@ConfigurationProperties还支持层级结构、 布尔、集合等类型的值注入
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties
@Configuration | @Value | |
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定(松散语法) | 支持 | 不支持 |
SPEL语法 | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂类型封装 | 支持 | 不支持 |
配置文件yml还是properties他们都能获取到值;
如果说, 只是在某个业务逻辑中需要获取一项配置文件中的某项值, 使用@Value
如果说,专门编写了一个javaBean 来和配置文件进行映射,我们就直接使用@ConfigurationProperties;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Component @ConfigurationProperties(prefix = "person") @Validated public class Person {
/** * <bean class="Person"> * <property name="lastName" value="字面值/${key} 从环境变量,配置文件中获取值/#{Spel}"></property> * </bean> */ //Value("${person.last-name}") //lastName必须为邮箱格式 private String lastName; //@Value("#{11*2}") private Integer age; //@Value("true") private Boolean boss; private Date birth; private Map<String, Object> maps; private List<Object> list; private Dog dog; |