本篇blog屬于個(gè)人工作時(shí)的經(jīng)驗(yàn)之談,在使用Maven進(jìn)行項(xiàng)目構(gòu)建Spring項(xiàng)目中遇到的啟動(dòng)問題,純屬個(gè)人見解。
項(xiàng)目結(jié)構(gòu)
在實(shí)際開發(fā)中,往往是用Maven來進(jìn)行構(gòu)建項(xiàng)目,一個(gè)項(xiàng)目一般都由多個(gè)Maven module組成,例如:
- xxx-base(項(xiàng)目啟動(dòng)module,以下為當(dāng)前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
項(xiàng)目啟動(dòng)
xxx-base的spring配置文件:
- 報(bào)錯(cuò)方式配置
<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"/>
異常如下圖:

錯(cuò)誤異常
- 解決方案
在存在PropertyPPlaceholderConfigure Bean的每個(gè)配置文件中都加上<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>
- 自動(dòng)掃描spring配置文件
當(dāng)一個(gè)工程引用的module過多時(shí),那么需要import的spring配置文件就特別多,這時(shí)可以將每個(gè)module的配置文件都使用相同的命名,例如applicationContext.xml,
在項(xiàng)目啟動(dòng)時(shí)通過如下代碼啟動(dòng):
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
這樣就可以去除掉一大串的import標(biāo)簽了。