一、基本原理和实现逻辑
二、Spring 容器初始化流程源码阅读
Spirng 容器初始化主要包括一下几个主要部分:bean实例化过程、bean的创建流程、bean的依赖注入流程、bean的初始化过程。
2.1 主流程源码分析
源码入口
//1. 创建IOC容器,并进行初始化ApplicationContext context = new ClassPathXmlApplicationContext("");//2. 获取创建的对象进行使用User user = context.getBean("beanName");
ClassPathXmlApplicationContext 构造方法
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {@Nullableprivate Resource[] configResources;// 根据String 类型的构造方法,读取bean.xml 配置文件进行后面的初始化操作public ClassPathXmlApplicationContext(String configLocation) throws BeansException {// 调用本方法构造方法this(new String[] {configLocation}, true, null);}public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)throws BeansException {// 实现父类构造方法,由于继承关系比较多,一层层实现最终到顶级父类super(parent);setConfigLocations(configLocations);if (refresh) {refresh();}}}
AbstractApplicationContext
public abstract class AbstractApplicationContext extends DefaultResourceLoaderimplements ConfigurableApplicationContext {@Overridepublic void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// Prepare this context for refreshing.// 1. 刷新预处理prepareRefresh();// Tell the subclass to refresh the internal bean factory.// 2:初始化流程1)创建IOC容器(DefaultListableBeanFactory)2) 加载解析XML文件(最终存储到Document对象中)3)读取Document对象,并完成BeanDefinition的加载和注册工作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.//11 实例化剩余的单例bean(非懒加载方式)//注意事项: bean的IoC、DI和AOP都发在此步骤中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();}}}}
2.2 创建BeanFactory流程源码分析
2.3 加载BeanDifination 流程分析
2.4 Bean 实例化流程分析
