本篇blog屬于個人工作時的經(jīng)驗之談袍睡,在使用Maven進行項目構建Spring項目中遇到的啟動問題,純屬個人見解双吆。
項目結構
在實際開發(fā)中在塔,往往是用Maven來進行構建項目幻件,一個項目一般都由多個Maven module組成,例如:
- xxx-base(項目啟動module蛔溃,以下為當前module依賴的module)
- xxx-common
- xxx-service(spring配置文件绰沥,屬性properties文件)
- ...
xxx-service的spring配置文件:
<context:component-scan base-package="xxx.xxx.xxx" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:properties/xxx.properties</value>
</list>list>
</property>
</bean>
xxx-service的properties文件:
redis.host=${redis.host}
redis.port=${redis.port}
redis.password=${redis.password}
redis.timeout=100000
redis.pool.maxIdle=600
redis.pool.maxTotal=1500
項目啟動
xxx-base的spring配置文件:
- 報錯方式配置
<context:component-scan base-package="xxx.xxx" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/xxx.properties</value>
</list>
</property>
</bean>
<import resource="classpath:xxx-applicationContext.xml"/>
異常如下圖:
錯誤異常
- 解決方案
在存在PropertyPPlaceholderConfigure Bean的每個配置文件中都加上<property name="ignoreUnresolvablePlaceholders" value="true" />
篱蝇,如下所示:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:properties/xxx.properties</value>
</list>
</property>
</bean>
- 自動掃描spring配置文件
當一個工程引用的module過多時,那么需要import的spring配置文件就特別多徽曲,這時可以將每個module的配置文件都使用相同的命名零截,例如applicationContext.xml
,
在項目啟動時通過如下代碼啟動:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
這樣就可以去除掉一大串的import標簽了秃臣。