l 主流程入口:
ApplicationContext context = new ClassPathXmlApplicationContext(“spring.xml”)
l ClassPathXmlApplicationContext类:重载的构造方法依次调用,进入下面代码
l AbstractApplicationContext的refresh方法:初始化spring容器的核心代码
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //1、 Prepare this context for refreshing.
prepareRefresh(); //创建DefaultListableBeanFactory(真正生产和管理bean的容器)
//BeanDefinition处理
// 1 定位XML文件(Resource、ResourceLoader)
// 2 加载XML(Document、Dom4j解析)
// 3 从Document对象中解析BeanDefinition然后注册到BeanDefinitionRegistry(Map)
//通过NamespaceHandler解析自定义标签的功能(比如:context标签、aop标签、tx标签) //2、 Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//3、 Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory); try { //4、 Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory); //实例化并调用实现了BeanFactoryPostProcessor接口的Bean
//比如:PropertyPlaceHolderConfigurer(context:property-placeholer)
//就是此处被调用的,作用是替换掉BeanDefinition中的占位符(${})中的内容
//5、 Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory); //创建并注册BeanPostProcessor到BeanFactory中(Bean的后置处理器)
//比如:AutowiredAnnotationBeanPostProcessor(实现@Autowired注解功能)
//RequiredAnnotationBeanPostProcessor(实现@Required注解功能)
//这些注册的BeanPostProcessor
//6、 Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory); //7、 Initialize message source for this context.
initMessageSource(); //8、 Initialize event multicaster for this context.
initApplicationEventMulticaster(); //9、 Initialize other special beans in specific context subclasses.
onRefresh(); //10、 Check for listener beans and register them.
registerListeners(); //1 通过构造方法,创建Bean的实例。此处的Bean是非懒加载方式的单例Bean(未设置属性)
//2 填充属性(DI,依赖注入)---循环依赖(A中有B的依赖、B中有A的依赖)
//3 初始化实例(比如调用init-method方法)
// 调用BeanPostProcessor(后置处理器)对实例bean进行后置处理(AOP功能)
//11、 Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory); //12、 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();
}
}
}