Spring IoC源码分析-02深入源码流程分析
上篇已经讲了ioc实现原理、实现方法与实现流程
这篇以debug模式去深究执行流程
以xml配置模式为例
进入org.springframework.context.support.AbstractApplicationContext#refresh方法
断点进入org.springframework.context.support.AbstractApplicationContext#prepareRefresh方法
进入:org.springframework.context.support.AbstractApplicationContext#prepareRefresh
protected void prepareRefresh() {
// Switch to active.
// 记录当前时间和容器的状态
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
// 在上下文环境中初始化属性设置,其底层是个空方法,由具体的子类定义其实现。
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 验证属性的合法性
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
//保存一些早期的容器事件
this.earlyApplicationEvents = new LinkedHashSet<>();
}
返回refresh()方法:
进入:org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory
关键来了,创建beanFactory
进入:org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory
注:xml配置的回去实现AbstractRefreshableApplicationContext#refreshBeanFactory方法
进入:org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)方法将配置文件放入bean工厂中。
进入org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader) 读取xml 加载bean
进入:org.springframework.beans.factory.support.AbstractBeanDefinitionReader#loadBeanDefinitions(java.lang.String...)
进入:org.springframework.beans.factory.support.AbstractBeanDefinitionReader#loadBeanDefinitions(java.lang.String, java.util.Set<org.springframework.core.io.Resource>)
获取到三个bean
返回:org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)
这时已经获取到spring2.xml的bean
返回到org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory
在返回到:org.springframework.beans.factory.config.ConfigurableListableBeanFactory方法去获取BeanFactory并返回
进入:org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory
{
// Tell the internal bean factory to use the context's class loader etc.
// 告诉内部bean工厂使用上下文的类加载器等。
// 指定beanFactory的类加载器
beanFactory.setBeanClassLoader(getClassLoader());
//设置表达式解析器等
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// 使用上下文回调配置bean工厂 ,添加后置处理器 ApplicationContextAwareProcessor
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//设置忽略的自动装配的接口
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// BeanFactory接口未在普通工厂中注册可解析类型
// 注册可以解析的自动装配,我们能直接在任何组件中自动注入
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// beanFactory添加早期后置处理器 以便将内部bean检测为applicationlisteners ApplicationListenerDetector
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 添加编译时的 AspectJ
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
// 为类型匹配设置临时类加载器。
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
// 注册缺省环境bean
//给 beanfactory 中注册能用的一些组件
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME,
getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
返回到refresh方法中
进入:org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List<org.springframework.beans.factory.config.BeanFactoryPostProcessor>)方法:
{
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 如果有,请先调用BeanDefinitionRegistryPostProcessors。
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 调用beanFactory的后置处理器 BeanDefinitionRegistryPostProcessor
// 用户可以实现BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry 注册bean
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
// 用户实现了BeanFactoryPostProcessor 但没有实现BeanDefinitionRegistryPostProcessor
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 去容器中查询是否有实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//判断是否实现了PriorityOrdered
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 获取 ConfigurationClassPostProcessor 实现了BeanDefinitionRegistryPostProcessor
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
////限制性实现了 priorityOrdered 优先级接口的后置处理器
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 会调用ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry 解析注解,注册bean
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 去容器中查询是否有实现了Ordered接口的BeanDefinitionRegistryPostProcessor
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 排除被处理过的,并且实现了Ordered接口的
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 去容器中查询是否有排除实现PriorityOrdered和Ordered后的其他的BeanDefinitionRegistryPostProcessor
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 调用ConfigurationClassPostProcessor#postProcessBeanFactory
// 1. 增强@Configuration修饰的配置类 AppConfig--->AppConfig$$EnhancerBySpringCGLIB
// 2. 添加了后置处理器 ConfigurationClassPostProcessor.ImportAwareBeanPostProcessor
// 调用用户自定义实现的BeanDefinitionRegistryPostProcessor#postProcessBeanFactory
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 调用用户自定义实现BeanFactoryPostProcessor 但没有实现BeanDefinitionRegistryPostProcessor
// 的后置处理器的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
// 调用用上下文实例注册的工厂处理器 beanFactory没有实现BeanDefinitionRegistry
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// 去容器中查询是否有实现BeanFactoryPostProcessor的后置处理器
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 实现 PriorityOrdered
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 实现 Ordered
List<String> orderedPostProcessorNames = new ArrayList<>();
// 剩下的
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
//调用实现了PriorityOrdered的BeanFactoryPostProcessor#postProcessBeanFactory
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
//调用实现了Ordered的BeanFactoryPostProcessor#postProcessBeanFactory
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
//调用剩下的BeanFactoryPostProcessor#postProcessBeanFactory
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//方法实现在外层
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//获取所有的 bean后置处理器
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// 检查和统计后置处理器
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// bean 的后置处理器也有实现 priority和order接口的后置处理器,用来指定优先级
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
//将实现了 MergedBeanDefinitionPostProcessor 接口的后置处理器加入到internalPostProcessors
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 首先,注册实现priorityordered接口的beanPostProcessors。
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
//注册bean后置处理器到beanFactory
//beanFactory.addBeanPostProcessor(postProcessor);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 接下来,注册实现ordered接口的beanPostProcessors。
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 现在,注册所有常规beanpstprocessors。
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 最后,重新注册所有内部 beanpstprocessors。实现了 MergedBeanDefinitionPostProcessor 接口的后置处理器
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 注册一个ApplicationListenerDetector 来检查bean创建完成是否为侦听器,如果是将此bean 放入到容器中
// 将其移动到处理器链的末端(用于获取代理等)。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
下面进行实例化:
进入getbean方法 实际会去调用AbstractBeanFactory的getBean()方法。
然后去调用org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean方法去获取实例
进入:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)方法
返回进入else方法
进入else
进入
刚开始读取bean是有三个实体类,他会在创建一个去除一个如下:
返回
获取到第一个bean的实例
下面开始初填充和初始化实例bean了
返回实例bean:
org.springframework.beans.factory.support.AbstractBeanFactory#getObjectForBeanInstance执行这个方法
回到for循环
开始下一个bean的创建,这里说下我们配置文件中如果写了id 与name 并且不同,那么这两个都是可以获取到bean的
所有的bean初始化完成之后回调 实现SmartInitializingSingleton#afterSingletonsInstantiated
Spring IOC 容器源码总结:
1)、Spring 容器在启动的时候,先会保存所有注册来的 Bean 的定义信息;
■ Xml 注册bean:<bean>
■ 注解注册Bean:@Service、@Component、@Bean等等
2)、Spring 容器会在合适的时机创建 bean;
■ 用到这个 bean 的时候,利用 getBean 创建 bean ,创建好后保存在容器中。
■ 统一创建剩下所有bean 的时候,调用 finishBeanFactoryInitialization()
3)、后置处理器:BeanPostProcessor:每一个 bean 的创建完成,都会使用各种后置处理器进行处理,来增强bean 的功能:
■ AutowriteAnnotationBeanPostProcessor:处理自动注入;
■ AnnotationAwareAspectJAutoProxyCreator:来做AOP 功能;等等。。。
4)、事件驱动模型:ApplicationListener 事件监听。ApplicationEventMulticaster 事件派发。
总的来说就创建beanFactory 注册bean 实例化bean
图形示例。
=======end==========
持续学习与努力。。。
下期学习:BeanPostProcessor
BeanPostProcessor是Spring容器的一个扩展点,可以进行自定义的实例化、初始化、依赖装配、依赖
检查等流程,即可以覆盖默认的实例化,也可以增强初始化、依赖注入、依赖检查等流程。
ps:想学更多java高级知识请到源码学院bat.ke.qq.com
上一篇: Maya HeadUpDisplay
下一篇: Spring IOC 源码分析