Spring Boot 2 實踐記錄之 使用 ConfigurationProperties 注解將配置屬性匹配至配置類的屬性


在 Spring Boot 2 實踐記錄之 條件裝配 一文中,曾經使用 Condition 類的 ConditionContext 參數獲取了配置文件中的配置屬性。但那是因為 Spring 提供了將上下文對象傳遞給 matches 方法的能力。

對於其它的類,想要獲取配置屬性,可以建立一個配置類,使用 ConfigurationProperties 注解,將配置屬性匹配到該類的屬性上。(當然,也可以使用不使用 ConfigurationProperties 注解,而使用 @Value注解)

如果要使用 ConfigurationProperties 注解,需要先在 Application 類上添加 @EnableConfigurationProperties 注解:

@SpringBootApplication
@PropertySource(value = {"file:${root}/conf/${env}/application.properties", "file:${root}/conf/${env}/business.properties"})
@EnableConfigurationProperties
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

假設 properties 文件中有如下配置屬性:

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=2000
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0

創建 RedisProperties 類如下:

@Component
@ConfigurationProperties(prefix="spring.redis")
@Data
Class RedisProperties {
    private String host;
    private String port;
    private String password;
    private String timeout;
    private Map<?, ?> pool;
}

引入這個 Bean,就可以讀取到相應的屬性了。

注意,所有的屬性必須有 Setter 和 Getter 方法,上例中,使用了 lombok 的 Data 注解,它會自動為私有屬性添加 Setter 和 Getter 方法)。

還要注意屬性的類型,如果是獲取最后一級的配置屬性,類型為 String,如果不是最后一級,則類型為 Map。

import lombok.extern.slf4j.Slf4j;

@Slf4j
Class RedisPropertiesTest {
    @Autowired
    private RedisProperties redisProperties;
    
    public void test() {
        log.info(redisProperties.getHost());
        Map<?, ?> pool = (Map) redisProperties.getPool();
        log.info(pool.get("min-idle").toString());
    }
}

打印出來的結果是:

127.0.0.1
0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM