springContextUtil版权声明

原创
小哥 3年前 (2022-11-11) 阅读数 46 #大杂烩

工具类用于获取bean,

applicationContext.xml

工具类:

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");

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门