ApplicationContextAware执行时机
一、为什么需要ApplicationContextAware?
在某些类中我们经常需要通过ApplicationContext来获取需要的bean,但每一次使用new ClassPathXmlApplicationContext()都会重新装配文件并实例化上下文bean,这样肯定是很麻烦的,此时ApplicationContextAware接口的作用就体现出来了——spring会给实现此接口的类注入ApplicationContext对象
二、如何使用?
通常我们是写一个ApplicationContextUtil工具类
public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext context; public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } public static ApplicationContext getContext() { return context; } }
三、spring何时注入上下文?
通过源码跟踪了解到AbstractApplicationContext.class下的refresh()方法中的prepareBeanFactory这句跟Aware有关,我们还可以看到:ApplicationContextAware是在spring初始化完bean后才注入上下文的
prepareBeanFactory方法中涉及到上图红圈圈这个类,此类中的方法postProcessBeforeInitialization调用了此类中的invokeAwareInterfaces方法:
看到没,上图画圈圈的地方就是spring对实现ApplicationContextAware接口的类调用setApplicationContext进行上下文注入