spring加载*.yml和*.properties文件

原理分析:

    Spring把加载的*.properties和*.yml文件加载到PropertyPlaceholderConfigurer,通过@Value("${...}")或@ConfigurationProperties(prefix="xxx", ignoreUnknownFields=false)获取加载的配置项.

1. @PropertySource(value={"classpath:xxx.properties", "classpath:application.properties"}, ignoreResourceNotFound=true,encoding="utf-8")
PropertyPlaceholderConfigurer类xml配置如下:
<bean id="propertyConfigure" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="fileEncoding" value="UTF-8" />
<property name="locations">
<list>
<value>classpath:xxx.properties</value>
</list>
</property>
</bean>
@PropertySource加载配置文件,相当于xml注解中在PropertyPlaceholderConfigurer类的locations列表中增加配置文件路径
2. @ConfigurationProperties(prefix="xxx",ignoreUnknownFields=false)

SpringBoot1.5以上版本@ConfigurationProperties取消location加载配置文件,只用作被注解类的属性填充,而使用@PropertySource加载配置文件


4.所有的配置项都可以通过Environment获取

import org.springframework.core.env.Environment;

@Autowired  
private Environment env; 

String name = env.getProperty("name");


注意 :
1.@ConfigurationProperties不会将被注解对象注册到ioc容器,只是将加载的配置文件内容注入对应的类属性,可以配合@Component或@Configuration注解进行bean注册

2.@EnableConfigurationProperties(*.class)会把被@ConfigurationProperties注解的配置类注入到ioc容器,可以使用@Autowired注入

3.@Value不能直接注入static属性,可以加在对应的set方法上注入.

如: 

private String name;

@Value("${name}")

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

属性为private,但不为static时也可以直接注入.

4.@PropertySource不能加载*.yml文件



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值