spring boot @ConfigurationProperties加载配置文件

    将指定前缀的配合信息注入到bean中,spring boot 1.5版本以前可以通过location属性指定配置文件路径,1.5以后configurationProperties删除了location属性,可以用@PropertySource来指定要读取的配置文件。

@Component
@ConfigurationProperties(prefix = "person")
@PropertySource("classpath:/env/dev2/application.properties")
public class Person {

    private String name;
    private int age;
    private List<String> address;
    private Map<String, String> map;

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public List<String> getAddress() {
        return address;
    }

    public void setAddress(List<String> address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address=" + address +
                ", map=" + map +
                '}';
    }
}

   这里spring会读取/env/dev2/application.properties配置文件中的person前缀的配置信息,address是一个list集合,map是一个map集合。@Compent会把personzhuce成bean,就可以在其他组件中注入使用。

person.name=abc
person.age=10
person.address[0]=北京
person.address[1]=上海
person.address[2]=广州
person.map.a=1
person.map.b=2

 

@configurationProperties也可以和@Bean配置和使用

    @Bean
    @ConfigurationProperties(prefix = "person")
    public Person getPerson() {
        return new Person();
    }


也可以从Environment对象中获取applicationContext中的配置信息,

@Component
public class TestEnvironment {
    private String name;
    @Autowired
    Environment environment;

    public String getName() {
        return environment.getProperty("default.redis.nodes");
    }
}
如果发现@ConfigurationPropertie不生效,有可能是项目的目录结构问题,你可以通过@EnableConfigurationProperties(ConnectionSettings.class)来明确指定需要用哪个实体类来装载配置信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值