How does ApplicationContextAware work in Spring?

后端 未结 4 540
醉话见心
醉话见心 2020-12-22 16:42

In spring, if a bean implements ApplicationContextAware, then it is able to access the applicationContext. Therefore it is able to get other beans.

4条回答
  •  悲哀的现实
    2020-12-22 17:19

    When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware and InitializingBean. If they are found, the methods are invoked. E.g. (very simplified)

    Class beanClass = beanDefinition.getClass();
    Object bean = beanClass.newInstance();
    if (bean instanceof ApplicationContextAware) {
        ((ApplicationContextAware) bean).setApplicationContext(ctx);
    }
    

    Note that in newer version it may be better to use annotations, rather than implementing spring-specific interfaces. Now you can simply use:

    @Inject // or @Autowired
    private ApplicationContext ctx;
    

提交回复
热议问题