大型項目中,咱們每每會對咱們的系統的配置信息進行統一管理,通常作法是將配置信息配置與一個cfg.properties的文件中,而後在咱們系統初始化的時候,系統自動讀取cfg.properties配置文件中的key value(鍵值對),而後對咱們系統進行定製的初始化。java
那麼通常狀況下,咱們使用的java.util.Properties,也就是java自帶的。每每有一個問題是,每一次加載的時候,咱們都須要手工的去讀取這個配置文件,一來編碼麻煩,二來代碼不優雅,每每咱們也會本身建立一個類來專門讀取,並儲存這些配置信息。spring
可是,在於我看來,這些本來Spring就有的東西,你還本身重複造輪子,費功夫。並且未必沒有那麼方便維護和管理升級。
用起來的通用性比較差,各個企業有各個企業的開發規範,這樣子一來,學習成本也提升。(這個是廢話)。
Spring中提供着一個PropertyPlaceholderConfigurerapp
這個類是BeanFactoryPostProcessor的子類。(不懂本身度娘,可瞭解可不瞭解,下面我會講大概)框架
其主要的原理在是。Spring容器初始化的時候,會讀取xml或者annotation對Bean進行初始化。
初始化的時候,這個PropertyPlaceholderConfigurer會攔截Bean的初始化,
初始化的時候會對配置的${pname}進行替換,根據咱們Properties中配置的進行替換。從而實現表達式的替換操做 。
瞭解完原理以後,咱們來看其實現的幾種方式。學習
在咱們的classpath下新建一個cfg.properties測試
#cfg.properties配置文件的內容 username=jay password=123
下面是Spring配置文件代碼編碼
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <!-- 對於讀取一個配置文件採起的方案 --> <property name="location" value="classpath:cfg.properties"></property> <!-- 對於讀取兩個以上配置文件採起的處理方案 --> <!-- <property name="locations"> <list> <value>classpath:cfg.properties</value> <value>classpath:cfg2.properties</value> </list> </property> --> </bean> </beans>
//測試代碼 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationCtx.xml") public class SpringCtxTst { @Value("${username}") private String uname; @Value("${password}") private String pwd; @Test public void test(){ System.out.println("username:"+uname); System.out.println("password:"+pwd); } }
控制檯輸出spa
username:jay password:123
固然,Spring 爲此也爲咱們提供了另一個的解決方案,咱們直接在Spring 配置文件中書寫以下代碼便可實現code
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!--採用這種方式簡化配置文件--> <context:property-placeholder location="classpath:cfg.properties,classpath:cfg2.properties"/> </beans>
咱們知道,不管是使用PropertyPlaceholderConfigurer仍是經過context:property-placeholder這種方式進行實現,都須要記住,Spring框架不單單會讀取咱們的配置文件中的鍵值對,並且還會讀取Jvm 初始化的一下系統的信息。有時候,咱們須要將配置Key定一套命名規則 ,例如xml
項目名稱.組名.功能名=配置值 org.team.tfunction=0001
這種方式來儘可能減小與系統配置信息的衝突!
同時,咱們也可使用下面這種配置方式進行配置,這裏我配NEVER的意思是不讀取系統配置信息。若是
<context:property-placeholder location="classpath:cfg.properties,classpath:cfg2.properties"
system-properties-mode="NEVER"/>