代码改变世界

如何通过Spring读取Properties文件

2016-08-23 16:20  爱车龟速兔  阅读(410)  评论(0编辑  收藏  举报
1 在Spring中配置文件中, 配置配置文件的引用
    <util:properties id="settings" location="/WEB-INF/conf/custom.properties"></util:properties>


2 实现一个ApplicationContextAware 的接口实现

public class SpringContextHolder implements ApplicationContextAware {

private static final Logger logger = Logger.getLogger(SpringContextHolder.class);


private static ApplicationContext ctx=null;

public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringContextHolder.ctx=context;
}

private SpringContextHolder(){
}

public static ApplicationContext getCtx(){
return ctx;
}

public static Object getBean(String name){
return ctx.getBean(name);
}
}

关于 ApplicationContextAware 接口的作用 参见: http://www.blogjava.net/yangjunwei/archive/2013/08/23/403211.html

加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的

public void setApplicationContext(ApplicationContext context) throws BeansException 

方法,设置ApplicationContext对象。

前提必须在Spring配置文件中指定该类



3 在Spring 的配置文件中配置 ApplicationContextAware  的接口实现类的Bean
<bean id="springContextHolder" class="com.xxx.common.SpringContextHolder"/> 


4 调用ApplicationContextAware 接口的实现类的getbean 方法, 转换成properties对象, 即可读取
Properties properties = (Properties) SpringContextHolder.getBean("settings");

Ref
其他读取properties文件的方法参考一下链接
java 获取路径的各种方法: http://www.cnblogs.com/guoyuqiangf8/p/3506768.html
java读取properties文件方法和对比: http://shmilyaw-hotmail-com.iteye.com/blog/1899242
Spring自动注入properties文件: http://1358440610-qq-com.iteye.com/blog/2090955