1. 程式人生 > >spring載入*.yml和*.properties檔案

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");


注意:
[email protected]不會將被註解物件註冊到ioc容器,只是將載入的配置檔案內容注入對應的類屬性,可以配合@Component或@Configuration註解進行bean註冊

[email protected](*.class)會把被@ConfigurationProperties註解的配置類注入到ioc容器,可以使用@Autowired注入

[email protected]不能直接注入static屬性,可以加在對應的set方法上注入.

如: 

private String name;

@Value("${name}")

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

屬性為private,但不為static時也可以直接注入.

4.@PropertySource不能載入*.yml檔案