zoukankan      html  css  js  c++  java
  • springContextUtil

    工具类用来获取bean,

    applicationContext.xml

    <bean id="springContextUtil" class="com.hna.hka.rmc.common.util.SpringContextUtil" lazy-init="false"></bean>

    工具类:

    package com.hna.hka.rmc.common.util;
    
    import javax.servlet.ServletContext;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.web.context.ServletContextAware;
    
    /**
     * 从Spring容器中取得对象
     * @author weiyuan
     *
     */
    public class SpringContextUtil implements ApplicationContextAware,
            ServletContextAware {
    
        private static ApplicationContext applicationContext; // Spring上下文对象.静态变量,可在任何代码任何地方任何时候中取出ApplicaitonContext. 
    
        private static ServletContext servletContext;// 注入 系统上下文对象
        
        Log log = LogFactory.getLog(SpringContextUtil.class);
        /**
         * 实现ApplicationContextAware接口的回调方法,设置上下文环境
         * 
         * @param applicationContext
         * @throws BeansException
         */
        public void setApplicationContext(ApplicationContext applicationContext) {
            log.debug(" com.hna.hka.rmc.common.util.SpringContextUtil setApplicationContext "+applicationContext);
            SpringContextUtil.applicationContext = applicationContext;
        }
    
        /**
         * @return ApplicationContext
         */
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
        /**
         * 获取对象
         * 
         * @param name
         * @return Object 一个以所给名字注册的bean的实例
         * @throws BeansException
         */
        public static Object getBean(String name) throws BeansException {
            return applicationContext.getBean(name);
        }
    
        /**
         * 功能 : 实现 ServletContextAware接口,由Spring自动注入 系统上下文对象
         * 
         **/
        public void setServletContext(ServletContext servletContext) {
            SpringContextUtil.servletContext = servletContext;
        }
    
        /**
         * @return ServletContext
         */
        public static ServletContext getServletContext() {
            return servletContext;
        }
    }


    java调用:
    private Template template = (Template) SpringContextUtil.getBean("Template");
    
    
    
     
  • 相关阅读:
    spring揭秘 读书笔记 六 bean的一生
    分枝限界算法
    libLAS1.8.0 编译和配置(VS2013+Win7 64)(一)
    Unity学习笔记 之 发射小球碰撞物体的代码记录
    hdu1281 棋盘游戏 --- 最大匹配
    javascript设计模式
    3、Android中Activity的跳转
    2.11 确定运行计划
    php扩展之 pdo_mysql.so
    POJ 1061 青蛙的约会(扩展欧几里得)
  • 原文地址:https://www.cnblogs.com/kasher/p/7355967.html
Copyright © 2011-2022 走看看