本文歡迎轉載,轉載前請聯繫作者,經允許後方可轉載。轉載後請註明出處,謝謝! http://blog.csdn.net/colton_null 作者:喝酒不騎馬 Colton_Null from CSDN
最近的項目需要在Spring環境下讀取properties文件。以前寫過一篇博客是針對SpringBoot讀取配置文件的,而這次在一個閉源框架中(當然這個框架是基於Spring的)想要讀取properties文件,在網上試了幾種方法都沒有成功。後來發現應該是和這個閉源框架中的一些原有配置發生了衝突。
由於之前沒有接觸過Spring最原生的寫法,所以幾經周折,在原生方式下實現了properties配置文件的讀取。
一、創建一個配置文件
在resource目錄下創建一個配置文件myconfig.properties
a=1
b=2
二、配置PropertyPlaceholderConfigurer
在applicationContext.xml文件中,添加如下配置
<bean id="myconfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 對於讀取一個配置文件採取的方案 -->
<property name="location" value="classpath:myconfig.properties"></property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
<!-- 對於讀取兩個以上配置文件採取的處理方案 -->
<!--
<property name="locations">
<list>
<value>classpath:cfg.properties</value>
<value>classpath:cfg2.properties</value>
</list>
</property>
-->
</bean>
1.ignoreUnresolvablePlaceholders爲是否忽略不可解析的Placeholder,如配置了多個PropertyPlaceholderConfigurer,則需設置爲true
2.我在這裏使用一個配置文件的方案,如果有多個配置文件打開下面讀兩個配置文件的註釋即可。
三、創建一個配置文件類
創建一個MyProperties類
public class MyProperties {
private String a;
private String b;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
四、配置JavaBean
再回到applicationContext.xml文件中,添加如下配置
<bean id="myProperties" class="cn.aimacademy.spy.spyplatformsc.testdc.config.MyProperties">
<property name="a" value="${a}"/>
<property name="b" value="${b}"/>
</bean>
類的包路徑記得自行修改。
五、注入這個Bean,用get方法即可使用。
在需要使用配置文件屬性的類中注入MyProperties類,使用get方法即可獲取到該屬性。
public class TestDemo {
@Resource(name = "myProperties")
private MyProperties myProperties;
public voidtest(){
String str = myProperties.getA();
}
}
這裏str就能獲取到1這個值了。
以上就是Spring中讀取properties配置文件的方法之一。