spring类实现自动读取配置文件

在使用spring的时候,我们使用Properties配置器把properties文件装载到Spring的上下文中,如下:

<!-- Loads a Properties instance -->
    <util:properties id="evn" location="classpath:config/jndi.properties"></util:properties>
    <context:property-placeholder location="classpath:config/ejb.properties" />  

这样在Spring的配置文件中可以用表达式来获得load进来的properties内容,如下:

    <jee:jndi-lookup jndi-name="${ejb-name}"  id="login-loginBean"
        lookup-on-startup="true" cache="true" proxy-interface="${ejb-interface}"
        environment-ref="evn">
    </jee:jndi-lookup>

既然spring已经能把properties读到它的上下文,在配置文件中轻松地使用,那么是不是也可以想办法让我们在代码中也能取到这些值?


那我们何不利用这一点,让我们能从代码中也使用这些值。

整理一下思路:
1、准备好配置文件,将properties的值设置到Bean中
2、初始化Spring上下文,加载properties文件
3、可以通过相应的bean去访问需要的properties的值

第1点很简单,不多说
第2点初始化Spring上下文,有很多方式,大家可以根据自己的方式选择其一即可。

方式1:
FileSystemXmlApplicationContext——从指定的目录中加载
ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml");  
方式2:
ClassPathXmlApplicationContext——从classpath路径加载:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
方式3:
ServletContext servletContext = servlet.getServletContext();     
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  
方式4:
在spring和各种MVC整合的框架下,在我们自己写的代码中要使用ApplicationContext是不方便的。
spring有一个类   org.springframework.web.context.support.WebApplicationContextUtils
它有一个static的方法 getWebApplicationContext(ServletContext sc) 可以使我们得到一个ApplicationContext的引用,
但这个方法有一个参数ServletContext,它是Servlet容器提供的上下文,在非Servlet环境下是得不到的。
我们可以定义一个servlet,该servlet配置为被容器第一个加载,它可以得到ServletContext,从而得到ApplicationContext的引用,
我们再把这个引用保存在一个所用应用都能访问到的地方。

  
  
  1. package xxx.utils;
  2. import org.springframework.context.ApplicationContext;
  3. public class SpringBeanProxy {
  4.     private static ApplicationContext applicationContext;
  5.     
  6.     public synchronized static void setApplicationContext(ApplicationContext arg0) {
  7.         applicationContext = arg0;
  8.     }
  9.     
  10.     public static Object getBean(String beanName){
  11.         return applicationContext.getBean(beanName);
  12.     }
  13. }
  1. package xxx.servlets;
  2. import javax.servlet.ServletConfig;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import org.springframework.web.context.support.WebApplicationContextUtils;
  6. import xxx.utils.SpringBeanProxy;
  7. public class SpringBeanInitServlet  extends HttpServlet {
  8.     public void init(ServletConfig arg0) throws ServletException {
  9.         SpringBeanProxy.setApplicationContext(WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()));
  10.     }
  11. }
在web.xml中
  1.     <listener>
  2.         <listener-class>
  3.             org.springframework.web.context.ContextLoaderListener
  4.         </listener-class>
  5.     </listener>
  6.     <servlet>
  7.         <servlet-name>SpringBeanInitServlet</servlet-name>
  8.         <servlet-class>
  9.             xxx.SpringBeanInitServlet
  10.         </servlet-class>
  11.         <load-on-startup>1</load-on-startup>
  12.     </servlet>
由于listener先于servlet加载,所以可以确保SpringBeanInitServlet加载时spring已经初始化好了, 如果你使用的是servlet加载spring就要注意调整这两个servlet的启动顺序了。 这时可以在程序的任何地方,使用 SpringBeanProxy.getBean("beanName")得到一个bean了。

第3步,查资料知道Spring使用

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer  读取properties文件。

我们可以扩展这个类来满足我们的需求。  怎么办?继承!

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * @author     : jl 
  3.  * @group      : tgb8 
  4.  * @Date       : 2014-4-4 下午4:38:19 
  5.  * @Comments   : 方便开发人员使用可以使用PropertyConfigurer.getContextProperty()来取得上下文中的properties的值了。 
  6.  * @Version    : 1.0.0 
  7.  */  
  8. public class PropertyConfigure extends PropertyPlaceholderConfigurer {  
  9.     private static Map<String, Object> ctxPropertiesMap;  
  10.     @Override  
  11.     protected void processProperties(ConfigurableListableBeanFactory beanFactory,  
  12.             Properties props) throws BeansException {  
  13.         super.processProperties(beanFactory, props);  
  14.           
  15.         ctxPropertiesMap = new HashMap<String, Object>();  
  16.         for (Object key : props.keySet()) {  
  17.             String keyStr = key.toString();  
  18.             String value = props.getProperty(keyStr);  
  19.             ctxPropertiesMap.put(keyStr, value);  
  20.         }  
  21.     }  
  22.     public static Object getContextProperty(String name) {  
  23.         //初始化全局配置  
  24.         initApplicationContext("context-properties.xml");  
  25.         return ctxPropertiesMap.get(name);  
  26.     }  
  27.       
  28.     private static void initApplicationContext(String key) {  
  29.         CacheHandler cacheHandler = CacheHandler.getInstance();  
  30.         Cache cache = cacheHandler.getCacheByName("ApplicationContext");  
  31.           
  32.         //如果没有初始化ApplicationContext,则初始化,并放入缓存,防止下次再初始化  
  33.         if (cache == null) {  
  34.             System.out.println("创建ApplicationContext缓存");  
  35.             cache = cacheHandler.addCache("ApplicationContext");  
  36.             System.out.println("初始化ApplicationContext,key="+key);  
  37.             ApplicationContext context = new ClassPathXmlApplicationContext(  
  38.                     key);  
  39.             Element elementVal = new Element(key, context);  
  40.             cache.put(elementVal);  
  41.         }  
  42.     }  
  43. }  


那么我们如何在Spring中配置呢?

<bean id="configBean" class="common.tool.config.PropertyConfigure">
        <!-- <property name="location" value="classpath:url.properties" /> -->
        <property name="locations">
            <list>
                <value>url.properties</value>
                <value>wsdl.properties</value>
            </list>
        </property>
 </bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值