欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot如何通過@Value,@ConfigurationProperties獲取配置

 更新時間:2022年03月18日 17:24:47   作者:darkwb09  
這篇文章主要介紹了springboot如何通過@Value,@ConfigurationProperties獲取配置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

通過@Value,@ConfigurationProperties獲取配置

spring boot 獲取配置項值

使用版本是1.5.4

舉例一個線程池的配置:

在application.yml添加配置項及值

? ? # 線程池配置
? ? taskexecutor:
? ? ? corePoolSize: 5
? ? ? maxPoolSize: 10
? ? ? queueCapacity: 25

通過@Value 獲取值

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

通過@ConfigurationProperties 獲取值 

? ? @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及屬性關聯(lián),指定ignoreUnknownFields當有屬性未匹配到值時會拋出異常,用prefix指定配置項的前綴。

@ConfigurationProperties還支持層級結構、 布爾、集合等類型的值注入

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties

說下@ConfigurationProperties和@Value區(qū)別

 @Configuration@Value
功能批量注入配置文件中的屬性一個個指定
松散綁定(松散語法)支持不支持
SPEL語法不支持支持
JSR303數(shù)據校驗支持不支持
復雜類型封裝支持不支持

配置文件yml還是properties他們都能獲取到值;

如果說, 只是在某個業(yè)務邏輯中需要獲取一項配置文件中的某項值, 使用@Value

如果說,專門編寫了一個javaBean 來和配置文件進行映射,我們就直接使用@ConfigurationProperties;

配置文件注入值數(shù)據校驗

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
 
    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面值/${key} 從環(huán)境變量,配置文件中獲取值/#{Spel}"></property>
     * </bean>
     */
    //Value("${person.last-name}")
    //lastName必須為郵箱格式
    @Email
    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;

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論