`
zl378837964
  • 浏览: 187012 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

spring关于web容器获取ApplicationContext引用和Properties配置属性值

阅读更多

 

前言:考虑到Spring的强大是尽人皆知的,所以能用就不必造轮子了,只需要改造即可。

 

1、web中如何控制ApplicationContext

 

在spring框架整合下,自己写的代码中要使用ApplicationContext是不方便的,但是在org.springframework.web.context.support.WebApplicationContextUtils 中有一方法 getWebApplicationContext(ServletContext sc) 可以得到ApplicationContext引用;但此方法有一参数ServletContext,它是Servlet容器提供的上下文,所以非Servlet环境下是得不到的。

我们可以定义一个servlet,该servlet配置为被容器第一个加载,它可以得到ServletContext,从而得到ApplicationContext的引用

 

import org.springframework.context.ApplicationContext;
public class SpringBeanProxy {
    private static ApplicationContext applicationContext;
    
    public synchronized static void setApplicationContext(ApplicationContext arg) {
        applicationContext = arg;
    }
    
    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }
}

 

 

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.springframework.web.context.support.WebApplicationContextUtils;
import SpringBeanProxy;
public class SpringBeanInitServlet  extends HttpServlet {
    public void init(ServletConfig arg) throws ServletException {
        SpringBeanProxy.setApplicationContext(WebApplicationContextUtils.getWebApplicationContext(arg.getServletContext()));
    }
}

 在web.xml中配置如下,即可

 

 

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>SpringBeanInitServlet</servlet-name>
        <servlet-class>
            SpringBeanInitServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

 由于listener先于servlet加载,所以可以确保SpringBeanInitServlet加载时spring已经初始化好了,如果你使用的是servlet加载spring就要注意调整这两个servlet的启动顺序了。代码中使用 SpringBeanProxy.getBean("bean name")即可得到bean实例。

还有其他方式,如

 

从指定目录加载:
ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml");  
从classpath路径加载:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml") 

 

2、web中如何控制基于ApplicationContext的配置文件读取信息值

 

关于程序中加载spring,自定义类实现spring 配置文件中通配符${jdbc.name}类似的正确解析;但是代码里如何使用读取到的配置文件呢?读源码 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 以及向上找父类和接口会发现,配置都定义好了,只是 protected Properties[] localProperties; 

是继承使用,没法调用。

于是就只定义啦,配置如下:

 

   <bean id="propertyConfigurer" class="com.jd.app.server.util.AutoPorpertiesConfigurer">
        <property name="locations">
            <list>
                <value>classpath:XXX.properties</value>
            </list>
        </property>
        <property name="propValueController" ref="genePropValueController"/>
        <property name="fileEncoding" value="GBK" />
    </bean>

 具体定制如下:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by on 2016/7/14.
 */
public class AutoPorpertiesConfigurer extends PropertyPlaceholderConfigurer {
    private static Map<String,Object> ctxPropertiesMap;
    private PropValueController propValueController;
    private PropValueController defaultPropValueController = new DefaultPropValueController();

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {

        super.processProperties(beanFactoryToProcess, props);
        ctxPropertiesMap = new HashMap<String,Object>();
         if (propValueController==null)
             propValueController = defaultPropValueController;

        long index=0;
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            Object value = propValueController.transform(index,keyStr,props.getProperty(keyStr));
            ctxPropertiesMap.put(keyStr, value);
            index++;
        }
    }

    public static Object getContextProperty(String name) {
        return ctxPropertiesMap.get(name);
    }

    public void setPropValueController(PropValueController propValueController) {
        this.propValueController = propValueController;
    }
}

/**
 * 配置值转化处理
 */
interface PropValueController{
    public Object transform(long index, String key, String value) throws BeansException;
}

/**
 * 配置默认返回原string
 */
class DefaultPropValueController implements PropValueController{
    @Override
    public Object transform(long index, String key, String value) throws BeansException {
        return value;
    }

 

 

此类即完成了PropertyPlaceholderConfigurer的任务,同时又提供了上下文properties访问的功能;于是在Spring配置文件中把PropertyPlaceholderConfigurer改成AutoPorpertiesConfigurer 。

PropValueController 接口可以为以后方便定制属性文件值转换灵活使用;

定义使用即可:

String gene = (String) propertyConfigurer.getContextProperty(cateid);

 

其实,通过

ServletContext servletContext = servlet.getServletContext();     
WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

 也能获取上下文并取得配置,但是如上定义更直接明了,简单易使用。

 

 转载原链接http://zl378837964.iteye.com/blog/2312241

分享到:
评论

相关推荐

    Spring-Reference_zh_CN(Spring中文参考手册)

    5.4.1. 设置和获取属性值以及嵌套属性 5.4.2. 内建的PropertyEditor实现 5.4.2.1. 注册用户自定义的PropertyEditor 6. 使用Spring进行面向切面编程(AOP) 6.1. 简介 6.1.1. AOP概念 6.1.2. Spring AOP的功能和目标 ...

    ssh(structs,spring,hibernate)框架中的上传下载

    WEB-INF下的applicationContext.xml为Spring的配置文件,struts-config.xml为Struts的配置文件,file-upload.jsp为文件上传页面,file-list.jsp为文件列表页面。  本文后面的章节将从数据持久层->业务层->Web层的...

    Spring 2.0 开发参考手册

    5.4.1. 设置和获取属性值以及嵌套属性 5.4.2. 内建的PropertyEditor实现 6. 使用Spring进行面向切面编程(AOP) 6.1. 简介 6.1.1. AOP概念 6.1.2. Spring AOP的功能和目标 6.1.3. Spring的AOP代理 6.2. @...

    Spring中文帮助文档

    5.4.1. 设置和获取属性值以及嵌套属性 5.4.2. 内建的PropertyEditor实现 6. 使用Spring进行面向切面编程(AOP) 6.1. 简介 6.1.1. AOP概念 6.1.2. Spring AOP的功能和目标 6.1.3. AOP代理 6.2. @AspectJ支持 ...

    Spring API

    5.4.1. 设置和获取属性值以及嵌套属性 5.4.2. 内建的PropertyEditor实现 6. 使用Spring进行面向切面编程(AOP) 6.1. 简介 6.1.1. AOP概念 6.1.2. Spring AOP的功能和目标 6.1.3. AOP代理 6.2. @AspectJ支持 ...

    spring chm文档

    5.4.1. 设置和获取属性值以及嵌套属性 5.4.2. 内建的PropertyEditor实现 6. 使用Spring进行面向切面编程(AOP) 6.1. 简介 6.1.1. AOP概念 6.1.2. Spring AOP的功能和目标 6.1.3. Spring的AOP代理 6.2. @...

    公文传输系统velocity struts spring hibernate(lib太大只发截图自己去下)

    找到“dataSource”定义部分,根据实际情况修改数据库连接属性值,比如连接字符串url、用户名uername和密码password等。 1.1.3 文件上传路径配置 找到“uploadPath”定义部分,根据系统的发布路径来修改文件的上传...

    springboot参考指南

    配置随机值 ii. 23.2. 访问命令行属性 iii. 23.3. Application属性文件 iv. 23.4. 特定的Profile属性 v. 23.5. 属性占位符 vi. 23.6. 使用YAML代替Properties i. 23.6.1. 加载YAML ii. 23.6.2. 在Spring环境中使用...

    springmybatis

    MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plan Old Java Objects,普通的Java对象)映射成数据库中的记录. orm工具的基本思想 无论是用过的hibernate,mybatis,你都可以法相他们有一个...

    BOS 技术整理

    rc/main/resource 提供 config.properties 外部属性文件、log4j.properties 日志配置文件 配置文件如下: applicationContext.xml  struts2 注解 类上 @ParentPackage 包继承谁? extends=”struts-default...

    低清版 大型门户网站是这样炼成的.pdf

    2.2.2 struts 2属性配置文件struts.properties详解 55 2.2.3 struts 2核心配置文件struts.xml详解 57 2.3 struts 2应用开发实务 61 2.3.1 struts 2应用开发环境的搭建 62 2.3.2 struts 2应用基本开发步骤—搭建...

    jsp探针 ver0.1

    Class.forName("org.springframework.context.ApplicationContext"); supportSpring = true; } catch (ClassNotFoundException ex) { } try { Class.forName("org.loon.framework.Loon"); supportLoonframework = ...

Global site tag (gtag.js) - Google Analytics