Spring学习笔记 通过PropertyPlaceholderConfigurer来使用properties文件初始化Map类型属性

来源:互联网 发布:淘宝买家秀自慰器图片 编辑:程序博客网 时间:2024/06/05 02:02

头些天弄了个使用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,也就是使用了多个newClassPathXmlApplicationContext,因为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,谢谢啦