spring ApplicationContext中Bean的生命周期
Posted Prince_Chang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring ApplicationContext中Bean的生命周期相关的知识,希望对你有一定的参考价值。
AbstractApplicationContext
Spring的AbstractApplicationContext是ApplicationContext的抽象实现类,该抽象类的refresh方法定义了spring容器在加载配置文件后的各项处理过程
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { prepareRefresh(); // 初始化BeanFactory ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); prepareBeanFactory(beanFactory); try { postProcessBeanFactory(beanFactory); /** * 调用工厂后处理器: * 根据反射机制找出所有实现了BeanFactoryPostProcessor接口的Bean, * 并调用其postProcessBeanFactory()接口方法 */ invokeBeanFactoryPostProcessors(beanFactory); /** * 注册Bean后处理器: * 根据反射机制找出所有实现了BeanPostProcessor接口的Bean, * 并注册 */ registerBeanPostProcessors(beanFactory); // 初始化消息源:初始化容器的国际化消息资源 initMessageSource(); // 初始化Application事件广播器 initApplicationEventMulticaster(); // 初始化其他特殊的Bean,由具体子类实现 onRefresh(); // 注册事件监听器 registerListeners(); // 初始化所有单例的Bean,使用懒加载的除外 finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset ‘active‘ flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring‘s core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
以上是关于spring ApplicationContext中Bean的生命周期的主要内容,如果未能解决你的问题,请参考以下文章
Spring -- Spring相关API (ApplicationContext getBean)
spring BeanFactory 与ApplicationContext
BeanFactory and ApplicationContext in Spring