SpringContextHolder获取bean实例

时间:2025-03-16 08:33:51
package ;

import ;
import ;
import ;

import .;
import org.;
import org.;
import ;
import ;
import ;
import ;
import ;

import ;

/**
 * 以静态变量保存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 = ();

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

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

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

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

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

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

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

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

    <bean  class="" />  

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

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

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

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

      private static CacheManager cacheManager = ((CacheManager)("cacheManager"));

6、小结

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

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

如此就不能说说这个接口了:

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

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

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

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