1.整体流程概览
public AnnotationConfigApplicationContext(Class>... annotatedClasses) {
this();
register(annotatedClasses);
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) {
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.1、prepareRefresh()
刷新前的预处理
1)initPropertySources()初始化一些属性设置;子类自定义个性化的属性设置方法;
2)getEnvironment().validateRequiredProperties();检验属性的合法等
3)earlyApplicationEvents= new LinkedHashSet
2.2 obtainFreshBeanFactory()
获取BeanFactory
1)refreshBeanFactory();刷新【创建】BeanFactory;
110行:创建了一个this.beanFactory = new DefaultListableBeanFactory();
设置id;
2)getBeanFactory();返回刚才GenericApplicationContext创建的BeanFactory对象;
3)将创建的BeanFactory【DefaultListableBeanFactory】返回;
2.3 prepareBeanFactory(beanFactory)
BeanFactory的预准备工作(以上创建了beanFactory,现在对BeanFactory对象进行一些设置属性)
1)设置BeanFactory的类加载器、支持表达式解析器...
2)添加部分BeanPostProcessor【ApplicationContextAwareProcessor】
3)设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
4)注册可以解析的自动装配;我们能直接在任何组件中自动注入:
BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
5)添加BeanPostProcessor【ApplicationListenerDetector】
6)添加编译时的AspectJ;
7)给BeanFactory中注册一些能用的组件;
environment【ConfigurableEnvironment】、
systemProperties【Map
systemEnvironment【Map
2.4、postProcessBeanFactory(beanFactory)
BeanFactory准备工作完成后进行的后置处理工作
1)子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置
2.5、invokeBeanFactoryPostProcessors(beanFactory)
执行BeanFactoryPostProcessor的方法
BeanFactoryPostProcessor:BeanFactory的后置处理器。在BeanFactory标准初始化之后执行的;
两个接口:BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
1)先执行BeanDefinitionRegistryPostProcessor
1-1)83行:获取所有的BeanDefinitionRegistryPostProcessor;
1-2)86行:看先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor、postProcessor.postProcessBeanDefinitionRegistry(registry)
1-3)99行:在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor;
postProcessor.postProcessBeanDefinitionRegistry(registry)
1-4)109行:最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;postProcessor.postProcessBeanDefinitionRegistry(registry)
2)再执行BeanFactoryPostProcessor的方法
2-1)139行:获取所有的BeanFactoryPostProcessor
2-2)147行:看先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor、postProcessor.postProcessBeanFactory()
2-3)167行:在执行实现了Ordered顺序接口的BeanFactoryPostProcessor;postProcessor.postProcessBeanFactory()
2-4)175行:最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor;postProcessor.postProcessBeanFactory()
2.6、registerBeanPostProcessors(beanFactory)
注册BeanPostProcessor(Bean的后置处理器)【 intercept bean creation】
不同接口类型的BeanPostProcessor;在Bean创建前后的执行时机是不一样的
BeanPostProcessor、
DestructionAwareBeanPostProcessor、
InstantiationAwareBeanPostProcessor、(AOP和事务)
SmartInstantiationAwareBeanPostProcessor、
MergedBeanDefinitionPostProcessor【internalPostProcessors】、
1)189行:获取所有的 BeanPostProcessor;后置处理器都默认可以通过PriorityOrdered、Ordered接口来执行优先级
2)204行:先注册PriorityOrdered优先级接口的BeanPostProcessor;把每一个BeanPostProcessor;添加到BeanFactory中beanFactory.addBeanPostProcessor(postProcessor);
3)224行:再注册Ordered接口的
4)236行:最后注册没有实现任何优先级接口的
5)最终注册MergedBeanDefinitionPostProcessor;
6)注册一个ApplicationListenerDetector;来在Bean创建完成后检查是否是ApplicationListener,如果是applicationContext.addApplicationListener((ApplicationListener>) bean);
2.7、initMessageSource()
初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
1)718行:获取BeanFactory
2)719行:看容器中是否有id为messageSource的,类型是MessageSource的组件
如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource;
MessageSource:取出国际化配置文件中的某个key的值;能按照区域信息获取;
3)739行:把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale);以后可通过getMessage获取
2.8、initApplicationEventMulticaster()
初始化事件派发器
1)753行:获取BeanFactory
2)754行:从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster;
3)762行:如果上一步没有配置;创建一个SimpleApplicationEventMulticaster
4)763行:将创建的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入
2.9、onRefresh()
留给子容器(子类)
1)子类重写这个方法,在容器刷新的时候可以自定义逻辑;
2.10 registerListeners()
给容器中将所有项目里面的ApplicationListener注册进来
1)822行:从容器中拿到所有的ApplicationListener
2)824行:将每个监听器添加到事件派发器中;
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
3)832行:派发之前步骤产生的事件;
2.11 finishBeanFactoryInitialization(beanFactory)
初始化所有剩下的单实例bean
867行:beanFactory.preInstantiateSingletons();初始化后剩下的单实例bean
1)734行:获取容器中的所有Bean,依次进行初始化和创建对象
2)738行:获取Bean的定义信息;RootBeanDefinition
3)739行:Bean不是抽象的,是单实例的,是懒加载;
3-1)740行:判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;
3-2)760行:不是工厂Bean。利用getBean(beanName);创建对象
3-2-0)199行:getBean(beanName); ioc.getBean();
3-2-1)doGetBean(name, null, null, false);
3-2-2)246行: getSingleton(beanName)先获取缓存中保存的单实例Bean《跟进去其实就是从MAP中拿》。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来)
从private final Map singletonObjects = new ConcurrentHashMap(256);获取的
3-2-3)缓存中获取不到,开始Bean的创建对象流程;
3-2-4)287行:标记当前bean已经被创建(防止多线程同时创建,使用synchronized)
3-2-5)291行:获取Bean的定义信息;
3-2-6)295行:getDependsOn(),bean.xml里创建person时,加depend-on="jeep,moon"是先把jeep和moon创建出来
【获取当前Bean依赖的其他Bean;如果有按照getBean()把依赖的Bean先创建出来;】
3-2-7)启动单实例Bean的创建流程;
3-2-7-1)462行:createBean(beanName, mbd, args);
3-2-7-2)490行:Object bean = resolveBeforeInstantiation(beanName, mbdToUse);让BeanPostProcessor先拦截返回代理对象;
【InstantiationAwareBeanPostProcessor】:提前执行;
先触发:postProcessBeforeInstantiation();
如果有返回值:触发postProcessAfterInitialization();
3-2-7-3)如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象;调用4)
3-2-7-4)501行:Object beanInstance = doCreateBean(beanName, mbdToUse, args);创建Bean
a)541行:【创建Bean实例】;createBeanInstance(beanName, mbd, args);
利用工厂方法或者对象的构造器创建出Bean实例;
b)applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName);
c)578行:【Bean属性赋值】populateBean(beanName, mbd, instanceWrapper);
赋值之前:
c-1)拿到InstantiationAwareBeanPostProcessor后置处理器;
1305行:postProcessAfterInstantiation();
c-2)拿到InstantiationAwareBeanPostProcessor后置处理器;
1348行:postProcessPropertyValues();
=====赋值之前:===
c-3)应用Bean属性的值;为属性利用setter方法等进行赋值;
applyPropertyValues(beanName, mbd, bw, pvs);
d)【Bean初始化】initializeBean(beanName, exposedObject, mbd);
d-1)1693行:【执行Aware接口方法】invokeAwareMethods(beanName, bean);执行xxxAware接口的方法
BeanNameAware\BeanClassLoaderAware\BeanFactoryAware
d-2)1698行:【执行后置处理器初始化之前】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
BeanPostProcessor.postProcessBeforeInitialization();
d-3)1702行:【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);
1)是否是InitializingBean接口的实现;执行接口规定的初始化;
2)是否自定义初始化方法;
d-4)1710行:【执行后置处理器初始化之后】applyBeanPostProcessorsAfterInitialization
BeanPostProcessor.postProcessAfterInitialization();
3-2-7-5)将创建的Bean添加到缓存中singletonObjects;sharedInstance = getSingleton(beanName, ()跟进去
254行:addSingleton(),放到MAP中
ioc容器就是这些Map;很多的Map里面保存了单实例Bean,环境信息。。。。;
4)所有Bean都利用getBean创建完成以后;
检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated();
2.12 finishRefresh()
完成BeanFactory的初始化创建工作,IOC容器就创建完成
1)882行:initLifecycleProcessor();初始化和生命周期有关的后置处理器;LifecycleProcessor
默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】;如果没有就new DefaultLifecycleProcessor(),加入到容器;
自己也可以尝试写一个LifecycleProcessor的实现类,可以在BeanFactory
void onRefresh();
void onClose();
2)885行:getLifecycleProcessor().onRefresh();
拿到前面定义的生命周期处理器(BeanFactory);回调onRefresh();
3)888行:publishEvent(new ContextRefreshedEvent(this));发布容器刷新完成事件;
4)891行:liveBeansView.registerApplicationContext(this);
3.IOC容器流程总结
1.Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息
1)xml注册bean;
2)注解注册Bean;@Service、@Component、@Bean、xxx2.Spring容器会合适的时机创建这些Bean
1)用到这个bean的时候;利用getBean创建bean;创建好以后保存在容器中;
2)统一创建剩下所有的bean的时候;finishBeanFactoryInitialization();3.后置处理器——BeanPostProcessor
1)每一个bean创建完成,都会使用各种后置处理器进行处理;来增强bean的功能;
AutowiredAnnotationBeanPostProcessor:处理自动注入
AnnotationAwareAspectJAutoProxyCreator:来做AOP功能;
......
增强的功能注解:
AsyncAnnotationBeanPostProcessor
......4.事件驱动模型
ApplicationListener;事件监听;
ApplicationEventMulticaster;事件派发:
参考
- 1)享学课堂James老师笔记