Spring Boot 2 实践记录之 使用 ConfigurationProperties 注解将配置属性匹配至配置类的属性

在 Spring Boot 2 实践记录之 条件装配 一文中,曾经使用 Condition 类的 ConditionContext 参数获取了配置文件中的配置属性。但那是由于 Spring 提供了将上下文对象传递给 matches 方法的能力。html

对于其它的类,想要获取配置属性,能够创建一个配置类,使用 ConfigurationProperties 注解,将配置属性匹配到该类的属性上。(固然,也能够使用不使用 ConfigurationProperties 注解,而使用 @Value注解)redis

若是要使用 ConfigurationProperties 注解,须要先在 Application 类上添加 @EnableConfigurationProperties 注解:spring

@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 文件中有以下配置属性:app

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 类以下:less

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

引入这个 Bean,就能够读取到相应的属性了。spa

注意,全部的属性必须有 Setter 和 Getter 方法,上例中,使用了 lombok 的 Data 注解,它会自动为私有属性添加 Setter 和 Getter 方法)。code

还要注意属性的类型,若是是获取最后一级的配置属性,类型为 String,若是不是最后一级,则类型为 Map。htm

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
相关文章
相关标签/搜索