使用SpringContextHolder获取bean实例,解决@Autowired不能注入静态Bean

1,706 阅读2分钟

今天在一个utils包下的文件中写一个方法的时候想去使用@autowired注入一些对象,但发现不可以直接使用@Autowired,因为方法是static,方法中使用的对象也必须是static,但正常情况下@Autowired无法注入静态的bean,于是发现项目中用到了springContextHolder,通过使用

private static Constants constants = SpringContextHolder.getBean(Constants.class); 这个方法就可以拿到静态的contants对象,从而获取到其中的变量等内容。于是就仔细看了看SpringContextHolder。 下面是完整代码

复制代码 /**

  • Copyright © 2012-2014 JeeSite All rights reserved. */ package com.cmb.bip.utils;

import org.apache.commons.lang3.Validate; 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;

/**

  • 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.

*/ @Service @Lazy(false) public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

private static ApplicationContext applicationContext = null;


/**
 * 取得存储在静态变量中的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() {
    applicationContext = null;
}

/**
 * 实现ApplicationContextAware接口, 注入Context到静态变量中.
 */
@Override
public void setApplicationContext(ApplicationContext appContext) {
    applicationContext = appContext;
}

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

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

} 复制代码 看了看这个好像是跟网上的一样,应该是一个固定代码。 这里正常情况下应该去配置文件配置出SpringContextHolder的bean,比如

但我找了一圈发现我们的代码中没有,然后发现是我们使用了@Service。同时和这句
<context:component-scan base-package="com.cmb.bip"></context:component-scan>

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

文章转自:blog.csdn.net/chenyiminna…