spring方便我們的項目快速搭建,功能強大,自然也會是體系復雜!
這里說下配置文件properties管理的問題。
一些不涉及到代碼邏輯,僅僅只是配置數據,可以放在xxxx.properties文件里面,項目功能復雜的時候,往往properties文件很多,這時,就比較容易讓人困惑,有些properties的文件內容總是加載不起來,應用啟動時,就不斷爆出錯誤,說某某參數加載失敗,這個是什么原因呢?
其實,這個是spring配置的時候,org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer這個bean只會被加載一次。在spring的xml配置文件中,多處出現這個bean的配置,spring加載的時候,只會加載第一個,后面的就加載不了。
如何解決呢?其實很簡單,比如我的一個應用中,就有internal.properties和jdbc.properties兩個文件。按下面這種方式就可以解決:
1 <bean id="configRealm" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 2 <property name="locations"> 3 <list> 4 <value>classpath:conf/internal.properties</value> 5 <value>classpath:conf/jdbc.properties</value> 6 </list> 7 </property> 8 </bean> 9 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> 10 <property name="properties" ref="configRealm"/> 11 </bean>
若有多個,可以在list中類似紅色部分添加就可以了!
在這里,再多說一點,xml的配置問題,當然,不是功能問題,而是習慣問題!
大的基於spring的項目,往往有很多xml配置文件,比如DAO的,比如權限shiro的配置,比如redis的配置等等,在web.xml中的context-param字段,可以如下配置:
1 <context-param> 2 <param-name>contextConfigLocation</param-name> 3 <param-value>classpath:conf/spring-dao.xml,classpath:conf/spring-servlet.xml</param-value> 4 </context-param>
但是,更好的辦法,是將一些應用模塊的xml配置通過import resource的方式放在一個xml文件中,例如applicationContext.xml。比如,我的應用applicationContext.xml文件的內容:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xsi:schemaLocation=" 6 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 8 9 <bean id="configRealm" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 10 <property name="locations"> 11 <list> 12 <value>classpath:conf/internal.properties</value> 13 <value>classpath:conf/jdbc.properties</value> 14 </list> 15 </property> 16 </bean> 17 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> 18 <property name="properties" ref="configRealm"/> 19 </bean> 20 21 <import resource="applicationContext-springdata.xml"/> 22 <import resource="applicationContext-security.xml"/> 23 <import resource="applicationContext-ehcache.xml"/> 24 <import resource="applicationContext-task.xml"/> 25 <import resource="applicationContext-external.xml"/> 26 <import resource="applicationContext-message.xml"/> --> 27 </beans>
這個applicationContext.xml可以在web.xml中的context-param配置部分加載,如下:
1 <context-param> 2 <param-name>contextConfigLocation</param-name> 3 <param-value>classpath:conf/applicationContext.xml</param-value> 4 </context-param>
這樣子,就會使得項目的配置文件結構非常的清晰!