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

来源:互联网 发布:select二级联动php 编辑:程序博客网 时间:2024/05/22 17:03

原理分析:

    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文件