一、为什么需要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何时注入上下文?

  ApplicationContextAware执行时机

通过源码跟踪了解到AbstractApplicationContext.class下的refresh()方法中的prepareBeanFactory这句跟Aware有关,我们还可以看到:ApplicationContextAware是在spring初始化完bean后才注入上下文的

ApplicationContextAware执行时机

prepareBeanFactory方法中涉及到上图红圈圈这个类,此类中的方法postProcessBeforeInitialization调用了此类中的invokeAwareInterfaces方法:

ApplicationContextAware执行时机

看到没,上图画圈圈的地方就是spring对实现ApplicationContextAware接口的类调用setApplicationContext进行上下文注入

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-14
  • 2021-05-05
  • 2021-08-15
猜你喜欢
  • 2021-10-14
  • 2022-01-18
  • 2021-06-23
  • 2022-12-23
  • 2021-10-29
  • 2021-10-28
  • 2021-12-20
相关资源
相似解决方案