如何在Spring XML配置文件中配置ResourceBundleMessageSource多属性文件?
嘿,这个问题我熟!在Spring XML配置文件里加载多个properties文件其实挺顺手的,我给你两种常用的配置方式,你按需选就行:
方法1:用
<context:property-placeholder>批量加载(最常用) 这种方式会把所有properties文件里的键值对统一合并到Spring的环境变量里,你直接用${key}就能引用,非常省心。
只需要在XML里添加这个标签,用location属性指定多个文件路径,路径之间用逗号分隔即可:
<context:property-placeholder location="classpath:message.properties, classpath:query.properties" ignore-unresolvable="true"/> <!-- 可选:如果项目里还有其他未解析的属性时,避免报错中断 -->
敲黑板:如果两个文件里存在相同的key,后面的文件(比如这里的query.properties)会覆盖前面的(message.properties),这个优先级规则要记好哦。
方法2:用
<util:properties>单独加载(适合需要独立管理的场景) 如果你不想把两个文件的属性合并,而是想把它们作为独立的Properties对象来分别使用,就可以用这个方式。
首先得在XML根标签里引入util命名空间:
xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
然后分别加载两个properties文件:
<!-- 单独加载message.properties --> <util:properties id="messageProps" location="classpath:message.properties"/> <!-- 单独加载query.properties --> <util:properties id="queryProps" location="classpath:query.properties"/>
之后你可以把这两个独立的Properties对象注入到你的业务Bean里:
<bean id="myService" class="com.example.MyService"> <property name="messageProperties" ref="messageProps"/> <property name="queryProperties" ref="queryProps"/> </bean>
怎么在Bean里使用这些属性?
如果用方法1,直接在Bean的配置里用${key}引用即可:
<bean id="myController" class="com.example.MyController"> <property name="welcomeMsg" value="${welcome.message}"/> <!-- 来自message.properties --> <property name="querySql" value="${user.query.sql}"/> <!-- 来自query.properties --> </bean>
如果用方法2,在你的Java类里定义对应的Properties字段,加上setter方法就能接收注入:
public class MyService { private Properties messageProperties; private Properties queryProperties; public void setMessageProperties(Properties messageProperties) { this.messageProperties = messageProperties; } public void setQueryProperties(Properties queryProperties) { this.queryProperties = queryProperties; } // 使用时直接调用getProperty获取属性值 public String getWelcomeMsg() { return messageProperties.getProperty("welcome.message"); } }
这样配置完就能正常使用啦,有细节问题随时问!
内容的提问来源于stack exchange,提问作者sarma mrr
相关产品推荐
相关产品推荐

