spring中获取配置文件内容

在上一篇博客中,我们说了PropertyPlaceholderConfigurer类的作用,使用该类方便我们对配置文件的管理,然后我们在代码中如何获取属性文件的值呢?
既然PropertyPlaceholderConfigurer类可以加载properties文件,那自然我们可以自定义一个它的子类,在不影响它原来功能的情况下,存储我们需要的内容。

public MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
private static Map myProperties;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props) throws BeansException{
super.processProerties(beanFactoryToProcess,props);
myProperties=new HashMap();
for(Object key:props.keySet()){
String keySet = key.toString();
String value=props.getProperty(keySet);
myProperties.put(keySet,value);
}
}
public static Object getContextProperty(String name){
return myProperties.get(name);
}
}

有了这个类,我们就在BeanFactory中将原来的PropertyPlaceholderConfigurer类换成该类
<bean id="propertyConfigurer" class="MyPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
<list>
</property>
</bean>
至此我们实现了在不影响原来的框架的情况下将属性文件的内容放到了myProperties中一份。

但是MyPropertyPlaceholderConfigurer作为一个bean是存在于容器中的,因此我们需要获得容器的上下文环境。

//@Component(或者在BeanFactory中配置)
public class MyPropertiesUtil implements ApplicationContextAware{
public static final String KEY="propertyConfigurer";
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(Application applicationContext) throws BeansExcepton{
MyPropertiesUtil.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
public static String getValue(String key){
MyPropertyPlaceholderConfigurer cp=(MyPropertyPlaceholderConfigurer)applicationContext.getBean(KEY);
return cp.getApplicationContext(key).toString();
}
}

至此我们已经写好了可以在代码中使用的Util类,但是无缘无故框架不会加载你自定义的类
因此我们需要加@Component注释或者在BeanFactory中加入

<bean class="MyPropertiesUtil"/>

自此,我们可以使用MyPropertiesUtil.getValue(key)来获得自定义文件中的内容,但是注意:[color=red]这段代码不能在bean的属性中使用,比如某个bean中存在代码,定义属性private int pagesize=MyPropertiesUtil.getValue(key);这段代码会有时候对有时候错的情况,因为这两个bean(pagesize属性所在的类bean依赖myPropertiesUtil类的bean,但实际上myPropertiesUtil中ApplicationContext的注入是在所有bean创建之后的,所以会出现问题。)[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值