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
原文地址:https://www.cnblogs.com/matchless/p/10428163.html