spring ioc 容器之间不能共享properties文件的问题

先说一个现象,分别在spring.xml(父容器)与spring-mvc.xml(子容器) 配置读取properties文件,然后在spring.xml里面的一个bean中,注意一个属性,属性值使用占位符${aName},aName是spring-mvc.xml properties文件中的key。运行程序,你会发现报错:Could not resolve placeholder 'bName' in value "${bName}"

<!-- spring.xml -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<list>
			<value>classpath:a.properties</value>
		</list>
	</property>
	<!-- 是否忽略无法解析的占位符,默认false,即找不到${key}时,程序将抛出异常,如果为true,则不抛异常,此时${key}会作为字符串传入 -->
	<property name="ignoreUnresolvablePlaceholders" value="true"></property>
</bean>

<bean class="cn.fg.bean.Hello">
	<property name="name" value="${bName}"></property> <!-- bName在b.properties -->
</bean>
<!-- spring-mvc.xml -->
<context:property-placeholder location="classpath:b.properties"  />

<bean class="cn.fg.bean.Hello">
	<property name="name" value="${aName}"></property> <!-- aName在a.properties -->
</bean>

因此得出一个结论:容器之间是不能引用对方properties中的key作为占位符使用的。如何解决?

//自定义PropertyPlaceholderConfigurer
public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
	
	//定义一个静态properties
	private static Properties properties;

	//重写processProperties
	@Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
		properties = props; //静态properties赋值
        super.processProperties(beanFactoryToProcess, props);
    }

	//获取属性值
	public static String getProperty(String key) {
		return properties.getProperty(key);
	}
}
<!-- 使用自定义的PropertyPlaceholderConfigurer -->
<bean class="cn.fg.bean.MyPropertyPlaceholderConfigurer">
	<property name="locations">
		<list>
			<value>classpath:a.properties</value>
		</list>
	</property>
</bean>
MyPropertyPlaceholderConfigurer.getProperty("aName"); //在需要的地方调用

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值