@PropertiesSource註解讀取配置檔案中的資料
這是properties配置檔案。
資料結構。
注入物件。
或者:
使用物件獲取屬性值。
或者:
瞭解:=========================================
通過@PropertySource註解將properties配置檔案中的值儲存到Spring的 Environment中,Environment介面提供方法去讀取配置檔案中的值,引數是properties檔案中定義的key值。上面是讀取一個配置檔案,如果你想要讀取多個配置檔案,請看下面程式碼片段:
@PropertySource(value = {"classpath:spring/config.properties","classpath:spring/news.properties"})
在Spring 4版本中,Spring提供了一個新的註解——@PropertySources,從名字就可以猜測到它是為多配置檔案而準備的。
@PropertySources({
@PropertySource("classpath:config.properties"),
@PropertySource("classpath:db.properties")
})
public class AppConfig {
//something
}
另外在Spring 4版本中,@PropertySource允許忽略不存在的配置檔案。先看下面的程式碼片段:
@Configuration
@PropertySource("classpath:missing.properties")
public class AppConfig {
//something
}
如果missing.properties不存在或找不到,系統則會丟擲異常FileNotFoundException。
Caused by: java.io.FileNotFoundException:
class path resource [missiong.properties] cannot be opened because it does not exist
幸好Spring 4為我們提供了ignoreResourceNotFound屬性來忽略找不到的檔案
@Configuration
@PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)
public class AppConfig {
}
@PropertySources({
@PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),
@PropertySource("classpath:config.properties")
})