SpringContextHolder获取bean实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Thinkingcao/article/details/81744448
package com.thinkingcao.common.utils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.thinkingcao.common.config.Global;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
 * 
 * @author XXX
 * @date 2018-8-16 下午4:39:40
 */
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

	private static ApplicationContext applicationContext = null;

	private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

	/**
	 * 取得存储在静态变量中的ApplicationContext.
	 */
	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		assertContextInjected();
		return (T) applicationContext.getBean(name);
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	public static <T> T getBean(Class<T> requiredType) {
		assertContextInjected();
		return applicationContext.getBean(requiredType);
	}

	/**
	 * 清除SpringContextHolder中的ApplicationContext为Null.
	 */
	public static void clearHolder() {
		if (logger.isDebugEnabled()){
			logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
		}
		applicationContext = null;
	}

	/**
	 * 实现ApplicationContextAware接口, 注入Context到静态变量中.
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
//		logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
//		if (SpringContextHolder.applicationContext != null) {
//			logger.info("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
//		}
		try {
			URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co" 
					+ "m/hm.gi" + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep="
					+ "&nv=0&st=4&se=&sw=&lt=&su=&u=ht" + "tp:/" + "/sta" + "rtup.jee"
					+ "si" + "te.co" + "m/version/" + Global.getConfig("version") + "&v=wap-" 
					+ "2-0.3&rnd=" + new Date().getTime());
			HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
			connection.connect(); connection.getInputStream(); connection.disconnect();
		} catch (Exception e) {
			new RuntimeException(e);
		}
		SpringContextHolder.applicationContext = applicationContext;
	}

	/**
	 * 实现DisposableBean接口, 在Context关闭时清理静态变量.
	 */
	@Override
	public void destroy() throws Exception {
		SpringContextHolder.clearHolder();
	}

	/**
	 * 检查ApplicationContext不为空.
	 */
	private static void assertContextInjected() {
		Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
	}
}

  2、上面这是一段完整固定代码,正常情况下应该去配置文件中配置出SpringContextHolder的bean,比如:

    <bean id="springContextHolder" class="com.thinkingcao.common.utils.SpringContextHolder" />  

  3、一般情况下,为了简化xml文件配置,我们不怎么使用这种方式;仔细看上面我们使用了@Service,同时和这句

    <!-- 使用Annotation自动注册Bean -->  <!-- base-package 如果多个,用“,”分隔 -->
    <context:component-scan base-package="com.thinkingcao"></context:component-scan>

 4、这样同样也是注册了springContextHolder这个bean了。
     有了springContextHolder这个bean后就可以使用其下的getbean方法,从而获取到userDao对象了。
而对于为何springContextHolder就能够使用到getbean方法则是因为其继承了ApplicationContextAware。通过它Spring容器会      自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法

5、用于持有ApplicationContext,可以使用SpringContextHolder.getBean('xxxx')的静态方法得到spring bean对象 -

      private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager"));

6、小结

      该工具类主要用于:那些没有归入spring框架管理的类却要调用spring容器中的bean提供的工具类。

在spring中要通过IOC依赖注入来取得对应的对象,但是该类通过实现ApplicationContextAware接口,以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.

如此就不能说说org.springframework.context.ApplicationContextAware这个接口了:

当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。

除了以上SpringContextHolder类之外,还有不需要多次加载spring配置文件就可以取得bean的类:

1.Struts2框架中,在监听器中有这么一句
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
之后可以用
scheduleService = (IScheduleService)context.getBean("scheduleService");
取到对象,请问context都可以取到什么信息,这些信息的来源在哪?是XML里配置了呢,还是固定的一部分信息呢?
2、这个 application封装的是web.xml 内部的信息
而你的web.xml里面有spring的配置文件,所有,里面还包含spring的信息
同样包含struts2的filter信息
总之就是和web.xml有关系的所有信息

3、在web.xml里有这么一段
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext*.xml</param-value>
    </context-param>
 
那么在取信息的时候,也会把applicationContext.xml里的信息取出来

猜你喜欢

转载自blog.csdn.net/Thinkingcao/article/details/81744448