Spring IoC容器的初始化
Spring源码分析(一)中提到了很多类,比如BeanDefinition、BeanDefinitionReader、BeanDefintionParser、BeanWrapper等都是ApplicationContext中需要使用的类,都可以从Spring源码中的注释中了解
IoC容器的初始化时由前面介绍的AbstractApplicationContext.refresh方法来启动的,具体来说,这个启动包括Bean的加载过程和Bean的实例化过程:
- Bean的加载过程分为,BeanDefinition的Resource定位、载入和注册
- Bean的实例化过程分为,Bean的创建和依赖注入
refresh()源码:
@Override
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) {
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;
}
}
}
Bean加载过程
BeanDefinition的Resource定位
实现路径:refresh()=>obtainFreshBeanFactory()=>refreshBeanFactory()=>loadBeanDefinitions()….DefaultResourceLoader.getResource()
这个Resource定位指的是BeanDefinition的资源定位,它由ResourceLoader完成的
BeanDefinition的载入和解析
这个过程是把用户定义好的Bean表示成IoC容器内部的数据结构,即BeanDefinition
实现路径:refresh()=>obtainFreshBeanFactory()=>refreshBeanFactory()=>loadBeanDefinitions()
其中牵扯到很多类,XmlBeanDefinitionReader、BeanDefinitionParserDelegate等等,可以DeBug进去
最后会发现Spring也是用的ClassLoader加载的class文件,将class信息封装成BeanDefinition,也就是之前被注解的类通过读取class文件的方式在这被载入(在类ClassPathBeanDefinitionScanner中实现)
BeanDefinition在IoC容器中注册
实现路径:refresh()=>obtainFreshBeanFactory()=>refreshBeanFactory()=>loadBeanDefinitions()……DefaultListableBeanFactory.registerBeanDefinition
最终DeBug的话会调到该方法,哎,只能说Spring好深,DefaultListableBeanFactory继承了BeanDefinitionRegistry接口,处处可以发现Spring面向接口的编程思想,职责分明
/** Map of bean definition objects, keyed by bean name */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(64);
所有的BeanDefinition都会存放在这个ConcurrentHashMap中
总结
至此Bean的加载过程到此结束,下一章重点分析bean的实例化和依赖注入
转载请注明出处http://blog.csdn.net/qq418517226/article/details/42711067