spring載入外部properties配置檔案
阿新 • • 發佈:2019-02-19
在配置spring的時候有些配置屬性放到外部檔案中進行管理或許更合理,這種情況一般是在配置資料來源的時候,將資料來源的配置資訊儲存在配置檔案中,然後在spring中載入配置檔案讀取具體的值進行bean屬性的注入,這樣更有利於管理我們的配置資訊。spring是通過一個以實現的實體bean來載入外部配置檔案:org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
一下是一個簡單的例項:
配置檔案database.properties:
url=192.168.7.10 username=root password=123 otherattr=other
bean物件DataBaseConfig.java:
package cn.qing.spring.bean; public class DataBaseConfig { private String url; private String username; private String password; private String otherattr; @Override public String toString() { return "DataBaseConfig [url=" + url + ", username=" + username + ", password=" + password + ", otherattr=" + otherattr + "]"; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getOtherattr() { return otherattr; } public void setOtherattr(String otherattr) { this.otherattr = otherattr; } }
Spring中的配置資訊:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="database.properties"/> </bean> <bean id="dataBaseConfig" class="cn.qing.spring.bean.DataBaseConfig"> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <property name="otherattr" value="${otherattr}"/> </bean>
測試程式碼:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DataBaseConfig config = (DataBaseConfig)context.getBean("dataBaseConfig");
System.out.println(config.toString());
輸出結果:
DataBaseConfig [url=192.168.7.10, username=root, password=123, otherattr=other]
以上DataBaseConfig類中的各個屬性就是從外部配置檔案中注入的。通過這樣的方式,我們可以在spring容器啟動時就載入一些必須的配置資訊到對應的Bean物件中,然後再將這個bean注入到其他需要使用這些配置資訊的bean中使用。