使用@PropertySource
@PropertySource 為將PropertySource
添加到 Spring 的Environment
提供了一種方便的聲明性機制。
給定名為app.properties
的文件,其中包含鍵值對testbean.name=myTestBean
,以下@Configuration
類使用@PropertySource
,從而對testBean.getName()
的調用返回myTestBean
:
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
@PropertySource
資源位置中存在的任何${…}
占位符都是根據已針對該環境注冊的一組屬性源來解析的,如以下示例所示:
@Configuration
@PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
假定my.placeholder
存在於已注冊的屬性源之一(例如,系統屬性或環境變量)中,則占位符將解析為相應的值。如果不是,則使用default/path
作為默認值。如果未指定默認值並且無法解析屬性,則會引發IllegalArgumentException
。
查看源碼:
會發現源碼中,是4.3版本才有的,假如講到4.3以下要添加以下才能解析properties文件。
@Bean
public static PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
點進去查看源碼
2個參數的夠用
一個參數的構造
到最后實現的構造方法
加載配置文件的方法
static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)
throws IOException {
InputStream stream = null;
Reader reader = null;
try {
String filename = resource.getResource().getFilename();
if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
stream = resource.getInputStream();
persister.loadFromXml(props, stream);
}
else if (resource.requiresReader()) {
reader = resource.getReader();
persister.load(props, reader);
}
else {
stream = resource.getInputStream();
persister.load(props, stream);
}
}
finally {
if (stream != null) {
stream.close();
}
if (reader != null) {
reader.close();
}
}
}
看上面源碼是支持xml的,下面在詳細寫一下解析xml和yml