Maven多module下的Spring啟動(dòng)

本篇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配置文件:

  1. 報(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ò)誤異常
  1. 解決方案

在存在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>
  1. 自動(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)簽了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,537評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,262評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,926評論 25 709
  • 文章作者:Tyan博客:noahsnail.com 2.Introduction to the Spring Fr...
    SnailTyan閱讀 5,533評論 7 56
  • 今年初給自己許了一些本年的期望,其中一項(xiàng)是嘗試一個(gè)新鮮方向。然后沒想到,上帝響應(yīng)需求那么迅速,四月底作詞被Apps...
    楊夏閱讀 707評論 4 7

友情鏈接更多精彩內(nèi)容