Spring學習筆記 通過PropertyPlaceholderConfigurer來使用properties檔案初始化Map類型屬性

來源:互聯網
上載者:User

頭些天弄了個使用properties檔案初始化bean屬性的測試,在這兩天工作時正好需要將部分配置提取到properties檔案中的情況,但是其中一個屬性為Map類型,上網搜了很久也沒搜到類似初始化Map的方法,在找到初始化Map方法前,為了使系統可以繼續使用,臨時使用了添加init方法的辦法來對Map進行手工初始化工作。如下:

首先使帶有Map屬性的類實現InitializingBean介面。

程式碼片段:

public class SsoMailConfigImpl implements InitializingBean, SsoMailConfig{    private String userDomainMapInit; // 通過properties將Map通過類似形式格式化存入userDomainMapInit 0:mail.com.cn | 1:test.com.cn    private Map<String, String> userDomainMap; //通過afterPropertiesSet()方法將userDomainMapInit資料初始化到Map中}

然後實現InitializingBean中的afterPropertiesSet()方法

代碼:

 public void afterPropertiesSet() throws Exception    {        if(userDomainMapInit!=null && !"".equals(userDomainMapInit))        {        userDomainMap = new HashMap<String, String>();        String[] userDomainArr = userDomainMapInit.split("\\|");        String[] tempKeyValue;        for (String userDomainEntry : userDomainArr)        {            tempKeyValue = userDomainEntry.split(":");            if (tempKeyValue.length == 2)            {                userDomainMap.put(tempKeyValue[0].trim(), tempKeyValue[1].trim());            }        }        }    }

正常情況下由於預設Spring容器使用Singleton模式建立Bean所以這個方法只會被執行一次。但在實際生產環境中這方法被執行了多次。。懷疑架構以及工程設定檔中存在多次引用定義所致,具體原因待有時間會仔細查下,暫時在代碼中增加依賴變數是否已初始化的判斷

(0926備忘:查看了架構的代碼。代碼中根據模組之間依賴有限初始化被依賴的模組中Spring的bean,每個模組中建立了一個context,也就是使用了多個new
ClassPathXmlApplicationContext
,因為Spring中的Singleton是指每個Context中保證bean建立的唯一性,多個context會導致同一個bean的多次建立。架構這樣寫為了模組之間松耦合以及靈活性。在使用afterPropertiesSet()時需要額外注意。

spring設定檔程式碼片段:

<bean id="propertyFileForMailConfig"        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="location">            <value>ssomailconfig.properties</value>        </property>    </bean>    <bean id="emailConfig" class="com.neusoft.education.dcp.apps.sso.SsoMailConfigImpl">       <property name="userDomainMapInit" value='${USER_DOMAIN_MAP_INIT}' />    </bean>

具體使用properties檔案初始化屬性的記錄在:http://blog.csdn.net/arvinrong/article/details/7850802

我想一定還有更簡潔的方法實現properties對Map進行初始化,希望有這方面經驗的朋友給我留言或者Mail我,arvin.rong@gmail.com,謝謝啦


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.