Spring上下文ApplicationContext接口,初始化实现在AbstractApplicationContext中
初始化流程:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) { //线程安全
// Prepare this context for refreshing.
prepareRefresh();//初始化标记值和Environment
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //初始化BeanFactory并扫描BeanDefinitions
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);//为BeanFactory初始化属性值,并且添加各种回调处理器,如ApplicationAware等
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);//初始化BeanFactory后ApplicationContext自定义操作
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);//调用BeanFactoryPostProcessor,先调用BeanDefinitionRegistryPostProcessor,按PriorityOrdered->Ordered->None顺序调用,而后调用BeanFactoryPostProcessor,顺序与前面相同
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);//注册BeanPostProcessor,当BeanFactory.createBean被调用时,会依次调用BeanPostProcessor
// Initialize message source for this context.
initMessageSource();//若存在自定义MessageSource则用,否则取空
// 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);//初始化非lazy-init单例对象
// Last step: publish corresponding event.
finishRefresh();//发布刷新完成事件
}
}
}
具体逻辑:
1.prepareRefresh方法,主要作用:初始化各标记值,初始化Environment,从配置的propertySources读取配置
2.obtainFreshBeanFactory方法:获取新的BeanFactory,即初始化BeanFactory,refreshBeanFactory方法由具体类实现,在AbstractRefeshableApplicationContext中,将会扫描BeanDefinition
3.prepareBeanFactory方法,向BeanFactory中添加初始化必须的属性及Bean,如自动装配处理器、资源自动注入处理器、各种默认回调接口处理
4.自定义BeanFactory初始化后操作,添加BeanPostProcessor处理器ServletContextAwareProcessor
5.调用之前注册的BeanFactoryPostProcessor,实质上调用PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessor方法
(1)getBeanFactoryPostProcessor()方法获取默认上下文BeanFactoryProcessor列表
(2)invokeBeanFactoryPostProcessor方法调用,先调用所有BeanDefinitionRegistryPostProcessor对BeanDefinition操作,而后对所有由ApplicationContext.addPostProcessor方法添加的BeanFactoryPostProcessor执行postBeanFactory操作
a)BeanFactoryPostProcessor分类成常规和Registry
b)从BeanDefinitions中获取BeanDefinitionRegistryPostProcessor类型,如果实现PriorityOrdered接口表明属于优先级排序的PostProcessor,排序后加入到registryPostProcessors中,优先调用
&nb 来源: 链接:oschina
https://my.oschina.net/u/4407587/blog/4195913