1. 问题背景
在我们的web程序中,用 spring 来管理各个实例(bean), 有时在程序中为了使用已被实例化的 bean, 通常会用到这样的代码:
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext-common.xml");
AbcService abcService = (AbcService)appContext.getBean("abcService");
但是这样就会存在一个问题:因为它会重新装载applicationContext-common.xml
并实例化上下文 bean,如果有些线程配置类也是在这个配置文件中,那么会造成做相同工作的的线程会被启两次。一次是 web 容器初始化时启动,另一次是上述代码显示的实例化了一次。当于重新初始化一遍!产生了冗余。
2. 解决方法
不用类似 new ClassPathXmlApplicationContext()
的方式,从已有的spring上下文取得已实例化的bean。通过 ApplicationContextAware
接口进行实现。
当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得 ApplicationContext 中的所有 bean。换句话说,就是这个类可以直接获取 spring 配置文件中,所有有引用到的 bean 对象。
**
3. ApplicationContextAware 怎么用
(1)方法类 AppUtil 实现 ApplicationContextAware 接口
@Component
public class AppUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
applicationContext = arg0;
}
public static Object getObject(String id) {
Object object = null;
object = applicationContext.getBean(id);
return object;
}
}
【备注】**
(1)在spring 的配置文件中,注册方法类 AppUtil。之所以方法类 AppUtil 能够灵活自如地获取ApplicationContext,就是因为spring能够为我们自动地执行了setApplicationContext
。但是 spring 不会无缘无故地为某个类执行它的方法的,所以,就很有必要通过注册方法类 AppUtil 的方式告知 spring 有这样子一个类的存在。这里我们使用 @Component
来进行注册,或者我们也可以像下面这样在配置文件声明 bean:
<bean id="appUtil" class="com.htsoft.core.util.AppUtil"/>
(2)加载 Spring 配置文件时,如果 Spring 配置文件中所定义的 Bean 类实现了 ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用 ApplicationContextAware 接口中的
public void setApplicationContext(ApplicationContext context) throws BeansException
方法,获得 ApplicationContext 对象,ApplicationContext 对象是由 spring 注入的。前提必须在 Spring配置文件中指定该类。
(3)使用静态的成员 ApplicationContext 类型的对象。
4. 使用场景备注
从 ApplicationContextAware 获取ApplicationContext 上下文的情况,仅仅适用于当前运行的代码和已启动的Spring 代码处于同一个 Spring 上下文,否则获取到的 ApplicationContext 是空的。
比如我要为当前系统加入一个定时任务,定时刷新 Memcache 缓存。这个定时任务框架是公司的框架,下面是我的ApplicationContextAware 接口实现类:
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;//声明一个静态变量保存
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("applicationContext正在初始化,application:"+appContext);
this.applicationContext=applicationContext;
}
public static <T> T getBean(Class<T> clazz){
if(applicationContext==null){
System.out.println("applicationContext是空的");
}else{
System.out.println("applicationContext不是空的");
}
return applicationContext.getBean(clazz);
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
}
定时任务类如下,定时任务初始化的时候,首先会调用作业类的public static Object getObject()
方法返回作业类的实例。
@Component
public class RemoteCacheJob extends AbstractSaturnJavaJob {
@Autowired
private AdsRemoteCacheJob adsRemoteCacheJob;
@Autowired
private ILogService logService;
// 实例化的过程:系统会首先调用作业类的public static Object getObject()方法,
// 如果返回为null,则调用作业类的无参构造方法来实例化;否则直接使用getObject()方法返回的对象作为作业类实例。
public static Object getObject() {
return ApplicationContextUtil.getBean(RemoteCacheJob .class);
}
@Override
public void handleJavaJob(String jobName, Integer shardItem, String shardParam, SaturnJobExecutionContext shardingContext)
throws InterruptedException {
System.out.println("处理定时任务");
}
}
启动项目,Spring容器进行初始化,可以看到已经初始化了 ApplicationContext :
然后运行定时任务插件,首先去获取 ApplicationContext,但是此时的 applicationContext 是空的:
很显然,定时任务是没办法获取到项目所在 Spring 容器启动之后的ApplicationContext。
5. 生产使用实例
/**
* @description:spring context 上下文
*/
@Component
@Slf4j
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
/**
* 取得存储在静态变量中的 ApplicationContext
*/
public ApplicationContext getContext() {
return applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
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() {
log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
applicationContext = null;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
log.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
if (SpringContextHolder.applicationContext != null) {
log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:"
+ SpringContextHolder.applicationContext);
}
SpringContextHolder.applicationContext = applicationContext;
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
SpringContextHolder.clearHolder();
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
if (applicationContext == null) {
throw new IllegalArgumentException(
"applicationContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
}
}
// 从静态变量applicationContext中取得Bean
SpringContextHolder.getBean(BaseItemServiceImpl.class)
@Resource
SpringContextHolder springContextHolder;
// 获取加了此注解的类
Map<String, Object> beanMap = springContextHolder.getContext().getBeansWithAnnotation(TagEventAnnotation.class);