如何经过Spring读取Properties文件

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 接口中的html

public void setApplicationContext(ApplicationContext context) throws BeansException java

方法,设置ApplicationContext对象。web

前提必须在Spring配置文件中指定该类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


相关文章
相关标签/搜索