Spring的ApplicationContext加载Property文件

来源:互联网 发布:女生学软件测试怎么样 编辑:程序博客网 时间:2024/05/16 16:57

利用Spring的ApplicationContext加载Property文件,可以实现国际化和'热'加载文件(不用重启应用).Spring提供了ResourceBundleMessageSource和ReloadableResourceBundleMessageSource两个类加载property文件,后者提供了'热'加载以及指定编码等功能.

例子:配置文件

<!--        <bean id="messageSource"        class="org.springframework.context.support.ResourceBundleMessageSource">        <property name="basenames"> <list> <value>resource/msg1</value>        <value>resource/msg2</value> </list> </property> </bean>    -->    <bean id="messageSource"        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">        <property name="defaultEncoding" value="gbk" />        <property name="cacheSeconds" value="5" />               <property name="basenames">            <list>                <value>resource/msg1</value>                <value>resource/msg2</value>            </list>        </property>    </bean>
property文件:
#resource/msg1.propertiesmessage1=message1 value!#resource/msg1_zh_CN.propertiesmessage1=message1 changed value[CN]!#resource/msg2.propertiesmessage2=test place holder : {0}!
JAVA Bean:
public class ResourceTestBean {    private MessageSource resources;    public void setResources(MessageSource resources) {        this.resources = resources;    }    public void testMsg() {               String message1 = this.resources.getMessage("message1", null, "Default",                Locale.CHINA);        System.out.println(message1);               String message2 = this.resources.getMessage("message2",                new Object[] { "passed in value" }, "default", null);        System.out.println(message2);    }}
Spring的MessageSource的getMessage方法提供了丰富的功能:1,如果要加载的property项不存在,指定默认值.2,指定Locale(如果不指定,用JVM运行的机器上的local来决定)来决定加载不同版本的property文件.

另外,如果需要将一些配置从XML里移到property文件可以参考如下:
<context:property-placeholder location="classpath:config.properties" />    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"    destroy-method="close">    <property name="driverClass">        <value>${jdbc.driverClassName}</value>    </property>    <property name="jdbcUrl">        <value>${jdbc.dburl}</value>    </property>    <property name="user">        <value>${jdbc.dbusername}</value>    </property>    <property name="password">        <value>${jdbc.dbpassword}</value>    </property></bean>

如果是component scan方式的话,在JAVA中按如下引用
    @Value("${DEFAULT_MAIL_FOR_FROM}")
    private String mailFrom;
   

 

原创粉丝点击