Spring 生命周期
spring-ApplicationContext启动过程中的初始化流程。
spring 启动过程中主要调用AbstractApplicationContext中的refresh方法
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } } }
1. prepareRefresh() 用于设置spring启动时间并且设置active flag 为true
2. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 刷新beanFactory并返回.
3. prepareBeanFactory(beanFactory); 为beanFactory注入必要的依赖和配置信息。
4. postProcessBeanFacotry(beanFactory); 空实现,没有具体代码。(我的spring版本是3.05)
5.invokeBeanFactoryPostProcessors(beanFactory); 初始化并且调用实现了BeanFactoryPostProcessor接口的类。(诸如PropertyPlaceholderConfigurer)
6.registerBeanPostProcessors(beanFactory);注册实现了BeanPostProcessor的类。(下面将会用到)
7.
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
初始化spring容器中的信息。
8.finishBeanFactoryInitialization(beanFactory);
遍历spring配置文件中配置的bean.
1) 找到第一个配置的bean,进行调用默认构造函数进行初始化。
2)对该bean设置属性。(配置文件中配置的property属性)
3)
如果该bean实现了BeanNameAware接口,则调用bean的setBeanName方法。
如果该bean实现了BeanClassLoaderAware接口,则调用bean的setBeanClassLoader方法。
如果该bean实现了BeanFactoryAware接口,则调用bean的setBeanFactory方法。
4) 遍历spring配置文件中实现BeanPostProcessor接口的类(),然后调用每一个BeanPostProcessor实现类 的postProcessBeforeInitialization方法。值得一提的是ApplicationContextAwareProcessor也实现了BeanPostProcessor,并且如果你初始化容器是AbstractApplicationContext的子类则会默认载入ApplicationContextAwareProcessor。
5)如果该bean实现了InitializingBean,则会调用afterPropertiesSet方法。
6)若果该bean在配置文件中设置了init-method属性,则会调用该属性指定的方法。
7) 遍历spring配置文件中实现BeanPostProcessor接口的类(),然后调用每一个BeanPostProcessor实现类 的postProcessAfterInitialization方法。
8) 继续第二个bean ...
9.finishRefresh 结束刷新。