IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> 33行代码读懂@Autowired属性注入过程 -> 正文阅读

[开发测试]33行代码读懂@Autowired属性注入过程

测试用例1

测试用例:一个userController类,类里有个属性userService,被@autowired注解

@Component
public class UserController {

    @Autowired
    private UserService userService;

    public void testController(){

    }
}

测试用例2

测试用例:启动引导类,新建spring容器对象AnnotationConfigApplicationContext

@Configuration
@ComponentScan
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DemoApplication {
    public static void main( String[] args ) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DemoApplication.class);
        UserService userService = (UserService) ctx.getBean("userServiceImpl");
        UserInfo userInfo = (UserInfo) ctx.getBean("user_zhangsan");
        userService.save(userInfo);
    }
}

前置断点:创建userController对象

代码块1:main

@Autowired属性注入用于在userController类中注入userService属性,所以首先需要创建userController对象

参数:args=[]

package com.helloworld;

public class DemoApplication {

    public static void main( String[] args ) { //args=[];

"*******"AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DemoApplication.class);

        "(1) 新建spring容器对象,AnnotationConfigApplicationContext,参数是启动类的类名"

        "参数:annotatedClasses=class com.helloworld.DemoApplication,"

        UserService userService = (UserService) ctx.getBean("userServiceImpl");
        UserInfo userInfo = (UserInfo) ctx.getBean("user_zhangsan");
        userService.save(userInfo);
    }

}

代码块2:AnnotationConfigApplicationContext()

AnnotationConfigApplicationContext构造器,负责注册引导类或主配置类bean定义,并刷新容器

参数:annotatedClasses=class com.helloworld.DemoApplication,

package org.springframework.context.annotation;

public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry{

	public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { //annotatedClasses=class com.helloworld.DemoApplication,;
		this();
		register(annotatedClasses); //将配置类注册进BeanDefinitionMap中 	annotatedClasses=class com.helloworld.DemoApplication,; 

"*******"refresh();

		"(2) 核心方法,刷新spring容器"

	}

}

代码块3:refresh

搜集工程中的所有bean定义,并依次创建实例;

package org.springframework.context.support;

public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{

	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) { //`startupShutdownMonitor` 同步监视器用于“刷新”和“销毁”。
			// Prepare this context for refreshing.
				......
				onRefresh();

				// Check for listener beans and register them.
				registerListeners(); //10. 在所有注册bean中查找Listener bean,并注册到广播器中

				// Instantiate all remaining (non-lazy-init) singletons.

"***************"finishBeanFactoryInitialization(beanFactory); //11. 初始化剩下的 (non-lazy-init) 单例. 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;

				"(3) bean定义搜集完毕,开始创建实例"

				"参数:beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"


				// Last step: publish corresponding event.
				finishRefresh(); //12. 最后:完成刷新过程,通知生命周期处理器LifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) { //若mock的值以force开头,则进行强制降级处理
					logger.warn("Exception encountered during context initialization - " +
				......
				resetCommonCaches(); //Reset common introspection caches in Spring's core, since wemight not ever need metadata for singleton beans anymore...从我们开始,重置Spring核心中的常见内省缓存可能再也不需要单例bean的元数据......
			}
		}
	}

}

代码块4:finishBeanFactoryInitialization

实例化所有单例bean

参数:beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springfra…

package org.springframework.context.support;

public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{

	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { //beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;
		// Initialize conversion service for this context.
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
				......
		beanFactory.setTempClassLoader(null); //停止使用临时类加载器进行类型匹配

		// Allow for caching all bean definition metadata, not expecting further changes.
		beanFactory.freezeConfiguration(); //4.冻结所有bean定义,注册的bean定义不会被修改或进一步后处理,因为马上要创建 Bean 实例对象了 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

		// Instantiate all remaining (non-lazy-init) singletons.

"*******"beanFactory.preInstantiateSingletons(); //5.实例化所有剩余(非懒加载)单例对象 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;

		"(4) 实例化所有单例bean"

	}

}

代码块5:preInstantiateSingletons

遍历所有的bean设计图,判断是否是factoryBean,还是普通bean

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) { //1. 循环 PropertySources
			logger.trace("Pre-instantiating singletons in " + this);
				......
						if (isEagerInit) {
							getBean(beanName); //6.如果beanName对应的bean不是FactoryBean,只是普通Bean,通过beanName获取bean实例
						}
					}
				}
				else {

"*******************"getBean(beanName); //6.如果beanName对应的bean不是FactoryBean,只是普通Bean,通过beanName获取bean实例 	beanName=org.springframework.context.annotation.internalConfigurationAnnotationProcessor; beanName=org.springframework.context.annotation.internalAutowiredAnnotationProcessor; beanName=org.springframework.context.annotation.internalCommonAnnotationProcessor; beanName=org.springframework.context.event.internalEventListenerProcessor; beanName=org.springframework.context.event.internalEventListenerFactory; beanName=demoApplication; beanName=testAspect; beanName=userController; beanName=myBeanPostProcessor; beanName=myBeanFactoryPostProcessor; beanName=userServiceImpl; beanName=user_zhangsan; beanName=org.springframework.aop.config.internalAutoProxyCreator;

					"(5) userController是普通bean,不是factoryBean,继续执行getBean"

					"参数:name=userController"

				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) { //7.遍历beanNames,触发所有SmartInitializingSingleton的后初始化回调 	beanName=org.springframework.context.annotation.internalConfigurationAnnotationProcessor; beanName=org.springframework.context.annotation.internalAutowiredAnnotationProcessor; beanName=org.springframework.context.annotation.internalCommonAnnotationProcessor; beanName=org.springframework.context.event.internalEventListenerProcessor; beanName=org.springframework.context.event.internalEventListenerFactory; beanName=demoApplication; beanName=testAspect; beanName=userController; beanName=myBeanPostProcessor; beanName=myBeanFactoryPostProcessor; beanName=userServiceImpl; beanName=user_zhangsan; beanName=org.springframework.aop.config.internalAutoProxyCreator; 
			Object singletonInstance = getSingleton(beanName); //7.1 拿到beanName对应的bean实例 	singletonInstance=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 
			if (singletonInstance instanceof SmartInitializingSingleton) { //7.2 判断singletonInstance是否实现了SmartInitializingSingleton接口
				......
				}
			}
		}
	}

}

代码块6:getBean

do开头的方法,开始真正创建bean

参数:name=userController

package org.springframework.beans.factory.support;

public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{

	@Override
	public Object getBean(String name) throws BeansException { //name=userController;

"*******"return doGetBean(name, null, null, false); //获取name对应的bean实例,如果不存在,则创建一个

		"(6) do开头的方法,开始真正创建bean"

		"参数:name=userController"
		"参数:typeCheckOnly=false"

	}

}

代码块7:doGetBean

lamda表达式的函数式编程写法,实际执行创建bean方法

参数:name=userController

参数:typeCheckOnly=false

package org.springframework.beans.factory.support;

public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{

	@SuppressWarnings("unchecked")
	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, //name=userController;typeCheckOnly=false;
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

				......
						}
					}
				}

				// Create bean instance.
				if (mbd.isSingleton()) { //9.针对不同的scope进行bean的创建 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 

"*******************"sharedInstance = getSingleton(beanName, () -> {

					"(7) lamda表达式的函数式编程写法,实际执行创建bean方法"

					"参数:beanName=userController"

						try {
							return createBean(beanName, mbd, args); //9.3.4 创建bean实例
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							destroySingleton(beanName); //2.从单例缓存中删除该beanName对应的bean(如果有的话)
				......
			}
		}
		return (T) bean; //11.返回创建出来的bean实例对象
	}

}

代码块8:getSingleton

函数式编程写法,实际执行创建bean方法

参数:beanName=userController

package org.springframework.beans.factory.support;

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry{

	public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { //beanName=userController;
		Assert.notNull(beanName, "Bean name must not be null"); //beanName的非空判断,为空抛出一个运行时异常 	beanName=userController; 
		synchronized (this.singletonObjects) { //1.加锁,避免重复创建单例对象
			Object singletonObject = this.singletonObjects.get(beanName); //2.首先检查beanName对应的bean实例是否在缓存中存在,如果已经存在,则直接返回
				......
				boolean newSingleton = false; //首先将新的newSingleton设置为false 	newSingleton=false; 
				boolean recordSuppressedExceptions = (this.suppressedExceptions == null); //suppressedExceptions用于记录异常相关信息 	recordSuppressedExceptions=true; 
				if (recordSuppressedExceptions) {
					this.suppressedExceptions = new LinkedHashSet<>(); //创建异常列表
				}
				try {

"*******************"singletonObject = singletonFactory.getObject(); //6.执行singletonFactory的getObject方法获取bean实例

					"(8) 函数式编程写法,实际执行创建bean方法,参考@FunctionalInterface注解"

					"参数:beanName=userController"
					"参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"

					newSingleton = true; //标记为新的单例对象 	newSingleton=true; 
				}
				catch (IllegalStateException ex) {
					// Has the singleton object implicitly appeared in the meantime ->
					// if yes, proceed with it since the exception indicates that state.
					singletonObject = this.singletonObjects.get(beanName); //单例对象是否同时隐式出现 ->如果是,则继续进行,因为异常指示该状态。
					if (singletonObject == null) { //检查是否存在此单例对象
						throw ex;
				......
			}
			return singletonObject; //返回缓存中的实例
		}
	}

}

代码块9:createBean

主要执行对象创建前的处理器及创建对象实例

参数:beanName=userController

参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) //beanName=userController;mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];
			throws BeanCreationException {

				......
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {

"***********"Object beanInstance = doCreateBean(beanName, mbdToUse, args); //5.创建Bean实例(真正创建Bean的方法)

			"(9) lamda表达式真正执行的方法,创建对象实例"

			"参数:beanName=userController"
			"参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"

			if (logger.isTraceEnabled()) { //1. 循环 PropertySources
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance; //6.返回创建的Bean实例
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			// A previously detected exception with proper bean creation context already,
			// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
				......
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}

}

代码块10:doCreateBean

1.创建对象。2.执行对象创建后的处理器。3.填充对象属性

参数:beanName=userController

参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) //beanName=userController;mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null; //1.新建Bean包装类
		if (mbd.isSingleton()) { //9.针对不同的scope进行bean的创建 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); //2.如果是FactoryBean,则需要先移除未完成的FactoryBean实例的缓存
		}
		if (instanceWrapper == null) {

"***********"instanceWrapper = createBeanInstance(beanName, mbd, args); //3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper 	instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29];

			"(10) 找到userController的构造器,使用构造器反射创建实例,至此,准备工作完成"

		}
		final Object bean = instanceWrapper.getWrappedInstance(); //包装的实例对象
		Class<?> beanType = instanceWrapper.getWrappedClass(); //包装的实例对象的类型 	beanType=class com.helloworld.controller.UserController; 
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType; //(包可见的字段,用于缓存给定bean定义的确定类),缓存 	mbd.resolvedTargetType=class com.helloworld.controller.UserController; 
		}

		// Allow post-processors to modify the merged bean definition.
				......
		}

		return exposedObject; //4.返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身
	}

}

总结:

前置断点:创建userController对象

  1. DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
  3. AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
  4. AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
  5. DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
  6. AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
  7. AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
  8. DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
  9. AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
  10. AbstractAutowireCapableBeanFactory.doCreateBean()————instanceWrapper = createBeanInstance(beanName, mbd…

断点一:找到UserController类中的属性userService,封装成元数据

代码块11:doCreateBean

回到doCreateBean,执行对象创建后的处理器。

参数:beanName=userController

参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) //beanName=userController;mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];
			throws BeanCreationException {

		// Instantiate the bean.
				......
"***********"instanceWrapper = createBeanInstance(beanName, mbd, args); //3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper 	instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29];
			"(10)"

		}

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {

"*******************"applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); //Autowired注解正是通过此方法实现注入类型的预解析 	beanType=class com.helloworld.controller.UserController; mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController;

					"(11) 回到doCreateBean,userController对象创建完毕后,执行对象创建后的处理器"

					"参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"
					"参数:beanType=class com.helloworld.controller.UserController"
					"参数:beanName=userController"

				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true; //标注这个bd已经被MergedBeanDefinitionPostProcessor的后置处理器处理过那么在第二次创建Bean的时候,不会再次调用applyMergedBeanDefinitionPostProcessors 	mbd.postProcessed=true; 
			}
		}
				......
		}

		return exposedObject; //4.返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身
	}

}

代码块12:applyMergedBeanDefinitionPostProcessors

依次调用bean后置处理器

参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…

参数:beanType=class com.helloworld.controller.UserController

参数:beanName=userController

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) { //mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];beanType=class com.helloworld.controller.UserController;beanName=userController;
		for (BeanPostProcessor bp : getBeanPostProcessors()) { //7.1 应用后置处理器InstantiationAwareBeanPostProcessor 	bp=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp; //对指定bean的给定MergedBeanDefinition进行后置处理,@Autowire注解在这边对元数据进行预解析

"***************"bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName); //执行postProcessMergedBeanDefinition 	beanType=class com.helloworld.controller.UserController; mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController; beanType=class com.helloworld.controller.UserController; mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController; beanType=class com.helloworld.controller.UserController; mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController;

				"(12) 依次调用bean后置处理器"

				"参数:beanDefinition=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"
				"参数:beanType=class com.helloworld.controller.UserController"
				"参数:beanName=userController"

			}
		}
	}

}

代码块13:postProcessMergedBeanDefinition

@Autowired注解对应类的关键方法,查找userController类的自动装配属性userService,将其封装成元数据

参数:beanDefinition=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=fa…

参数:beanType=class com.helloworld.controller.UserController

参数:beanName=userController

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { //beanDefinition=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];beanType=class com.helloworld.controller.UserController;beanName=userController;

"*******"InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null); //1.在指定Bean中查找使用@Autowire注解的元数据 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d;

		"(13) 查找userController类的自动装配属性userService,封装成元数据"

		"参数:beanName=userController"
		"参数:clazz=class com.helloworld.controller.UserController"

		metadata.checkConfigMembers(beanDefinition); //2.检查元数据中的注解信息 	beanDefinition=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 
	}

}

代码块14:findAutowiringMetadata

根据userController类的userService属性,构建userController类的autowired自动装配元数据

参数:beanName=userController

参数:clazz=class com.helloworld.controller.UserController

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { //beanName=userController;clazz=class com.helloworld.controller.UserController;
		// Fall back to class name as cache key, for backwards compatibility with custom callers.
		String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); //1.设置cacheKey的值(beanName 或者 className) 	cacheKey=userController; 
		// Quick check on the concurrent map first, with minimal locking.
				......
			synchronized (this.injectionMetadataCache) {
				metadata = this.injectionMetadataCache.get(cacheKey); //4.加锁后,再次从缓存中获取beanName对应的InjectionMetadata
				if (InjectionMetadata.needsRefresh(metadata, clazz)) { //5.加锁后,再次检查InjectionMetadata是否需要刷新 	clazz=class com.helloworld.controller.UserController; 
					if (metadata != null) { //pvs是null前面写的传null
						metadata.clear(pvs); //6.如果需要刷新,并且metadata不为空,则先移除
					}

"*******************"metadata = buildAutowiringMetadata(clazz); //这里的元素包括AutowiredFieldElement和AutowiredMethodElement) 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d;

					"(14) 根据userController类的userService属性,构建userController类的autowired自动装配元数据"

					"参数:clazz=class com.helloworld.controller.UserController"

					this.injectionMetadataCache.put(cacheKey, metadata); //8.将解析的元数据放到injectionMetadataCache缓存,以备复用,每一个类只解析一次 	cacheKey=userController; metadata=org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
				}
			}
		}
		return metadata; //返回解析的作用域元信息对象 	org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
	}

}

代码块15:buildAutowiringMetadata

函数式编程,实际上执行的是findAutowiredAnnotation

参数:clazz=class com.helloworld.controller.UserController

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) { //clazz=class com.helloworld.controller.UserController;
		List<InjectionMetadata.InjectedElement> elements = new ArrayList<>(); //存放所有需要注入的元数据列表
		Class<?> targetClass = clazz; //目标类 	targetClass=class com.helloworld.controller.UserController; 

		do {
			final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>(); //保存完成注解解析的元素


"***********"ReflectionUtils.doWithLocalFields(targetClass, field -> { // 	targetClass=class com.helloworld.controller.UserController;

			"(15) 函数式编程,实际上执行的是findAutowiredAnnotation,执行这个方法后,第22行代码对执行结果进行封装;最后一行创建依赖注入元数据并返回"

			"参数:ao=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService"

				AnnotationAttributes ann = findAutowiredAnnotation(field); //2.2.1 获取field上的@Autowired注解信息
				if (ann != null) { //8.如果该候选者使用了@Autowire注解
					if (Modifier.isStatic(field.getModifiers())) { //2.2.2 校验field是否被static修饰,如果是则直接返回,因为@Autowired注解不支持static修饰的field
						if (logger.isInfoEnabled()) { //invoker 可用性检查
							logger.info("Autowired annotation is not supported on static fields: " + field);
						}
						return;
					}
				......
		while (targetClass != null && targetClass != Object.class);

		return new InjectionMetadata(clazz, elements); //2.7 将clazz和解析到的注入的元素封装成InjectionMetadata 	org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
	}

}

代码块16:findAutowiredAnnotation

获取autowire自动装配属性,即userService

参数:ao=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	@Nullable
	private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) { //ao=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService;
		if (ao.getAnnotations().length > 0) {  // autowiring annotations have to be local // 	ao=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService; 
			for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) { //2.检查是否有autowiredAnnotationTypes中的注解:@Autowired、@Value(@Value无法修饰构造函数) 	type=interface org.springframework.beans.factory.annotation.Autowired; 

"***************"AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type); //3.拿到注解的合并注解属性,@Autowire在这边拿到,required=true(默认属性) 	attributes=required=true;;

				"(16) 获取autowire自动装配属性,即userService"

				"参数:element=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService"
				"参数:annotationType=interface org.springframework.beans.factory.annotation.Autowired"

				if (attributes != null) { //如果使用了@Scope注解
					return attributes; //此处省略不相关逻辑………… 	required=true;; 
				}
			}
		}
		return null;
	}

}

代码块17:getMergedAnnotationAttributes

找到默认属性required=true

参数:element=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService

参数:annotationType=interface org.springframework.beans.factory.annotation.Autowired

package org.springframework.core.annotation;

public class AnnotatedElementUtils {

	@Nullable
	public static AnnotationAttributes getMergedAnnotationAttributes( //element=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService;annotationType=interface org.springframework.beans.factory.annotation.Autowired;
			AnnotatedElement element, Class<? extends Annotation> annotationType) {


"*******"AnnotationAttributes attributes = searchWithGetSemantics(element, annotationType, null, // 	attributes=required=org.springframework.core.annotation.AnnotationUtils$DefaultValueHolder@158a8276;;

		"(17) 找到@Autorwired默认属性required=true,至此找到被@Autowired注解的属性userService及注解的默认属性required=true,回到findAutowiringMetadata方法,放入缓存injectionMetadataCache"

				new MergedAnnotationAttributesProcessor());
		AnnotationUtils.postProcessAnnotationAttributes(element, attributes, false, false); // 	element=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService; attributes=required=true;; 
		return attributes; //此处省略不相关逻辑………… 	required=true;; 
	}

}

总结:

断点一:找到UserController类中的属性userService,封装成元数据

  1. DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
  3. AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
  4. AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
  5. DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
  6. AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
  7. AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
  8. DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
  9. AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
  10. AbstractAutowireCapableBeanFactory.doCreateBean()————applyMergedBeanDefinitionPostProcessors(mbd, beanT…
  11. AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()————bdp.postProcessMergedBeanDefinition(mbd, beanType,…
  12. AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition()————InjectionMetadata metadata = findAutowiringMetadat…
  13. AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata()————metadata = buildAutowiringMetadata(clazz);
  14. AutowiredAnnotationBeanPostProcessor.buildAutowiringMetadata()————ReflectionUtils.doWithLocalFields(targetClass, fie…
  15. AutowiredAnnotationBeanPostProcessor.findAutowiredAnnotation()————AnnotationAttributes attributes = AnnotatedElement…
  16. AnnotatedElementUtils.getMergedAnnotationAttributes()————AnnotationAttributes attributes = searchWithGetSem…

断点二:填充userController属性,准备依赖注入

代码块18:findAutowiringMetadata

将解析的元数据放到injectionMetadataCache缓存,以备复用

参数:beanName=userController

参数:clazz=class com.helloworld.controller.UserController

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { //beanName=userController;clazz=class com.helloworld.controller.UserController;
		// Fall back to class name as cache key, for backwards compatibility with custom callers.
		String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); //1.设置cacheKey的值(beanName 或者 className) 	cacheKey=userController; 
		// Quick check on the concurrent map first, with minimal locking.
				......
				metadata = this.injectionMetadataCache.get(cacheKey); //4.加锁后,再次从缓存中获取beanName对应的InjectionMetadata
				if (InjectionMetadata.needsRefresh(metadata, clazz)) { //5.加锁后,再次检查InjectionMetadata是否需要刷新 	clazz=class com.helloworld.controller.UserController; 
					if (metadata != null) { //pvs是null前面写的传null
						metadata.clear(pvs); //6.如果需要刷新,并且metadata不为空,则先移除
					}
"*******************"metadata = buildAutowiringMetadata(clazz); //这里的元素包括AutowiredFieldElement和AutowiredMethodElement) 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d;
					"(14)"


"*******************"this.injectionMetadataCache.put(cacheKey, metadata); //8.将解析的元数据放到injectionMetadataCache缓存,以备复用,每一个类只解析一次 	cacheKey=userController; metadata=org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d;

					"(18) 将解析的元数据放到injectionMetadataCache缓存,以备复用"

				}
			}
		}
		return metadata; //返回解析的作用域元信息对象 	org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
	}

}

总结:

断点二:填充userController属性,准备依赖注入

  1. DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
  3. AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
  4. AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
  5. DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
  6. AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
  7. AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
  8. DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
  9. AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
  10. AbstractAutowireCapableBeanFactory.doCreateBean()————applyMergedBeanDefinitionPostProcessors(mbd, beanT…
  11. AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()————bdp.postProcessMergedBeanDefinition(mbd, beanType,…
  12. AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition()————InjectionMetadata metadata = findAutowiringMetadat…
  13. AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata()————this.injectionMetadataCache.put(cacheKey, metadata…

断点三:根据元数据生成bean名称userService

代码块19:doCreateBean

再次回到doCreateBean方法,填充bean属性

参数:beanName=userController

参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) //beanName=userController;mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];
			throws BeanCreationException {

		// Instantiate the bean.
				......
"***********"instanceWrapper = createBeanInstance(beanName, mbd, args); //3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper 	instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29];
			"(10)"

"*******************"applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); //Autowired注解正是通过此方法实现注入类型的预解析 	beanType=class com.helloworld.controller.UserController; mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController;
					"(11)"

			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); //提前将创建的 bean 实例加入到ectFactory 中这里是为了后期避免循环依赖 	beanName=userController; 
		}

		// Initialize the bean instance.
		Object exposedObject = bean; //Initialize the bean instance.  初始化bean实例。
		try {

"***********"populateBean(beanName, mbd, instanceWrapper); //9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController; instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29];

			"(19) 再次回到doCreateBean方法,填充bean属性"

			"参数:beanName=userController"
			"参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"
			"参数:bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29]"

			exposedObject = initializeBean(beanName, exposedObject, mbd); //10.对bean进行初始化
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
				......
		}

		return exposedObject; //4.返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身
	}

}

代码块20:populateBean

遍历所有的后置处理器,尤其是AutowiredAnnotationBeanPostProcessor

参数:beanName=userController

参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…

参数:bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29]

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	@SuppressWarnings("deprecation")  // for postProcessPropertyValues
	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { //beanName=userController;mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29];
		if (bw == null) { //2.bw为空时的处理
			if (mbd.hasPropertyValues()) {
				......
			if (pvs == null) {
				pvs = mbd.getPropertyValues(); //如果为空,再次从BeanDefinition对象中获取,TODO? 	pvs=PropertyValues: length=0; 
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) { //7.1 应用后置处理器InstantiationAwareBeanPostProcessor 	bp=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 
				if (bp instanceof InstantiationAwareBeanPostProcessor) { //2.应用InstantiationAwareBeanPostProcessor后置处理器,允许postProcessBeforeInstantiation方法返回bean对象的代理
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //应用后处理器InstantiationAwareBeanPostProcessor,调用其postProcessPropertyValues方法作用是对需要进行依赖检查的属性进行处理Autowired等注解的属性就是在这里完成注入的 	ibp=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 

"*******************"PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); //这句就是核心 	pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0;

					"(20) 遍历所有的后置处理器,尤其是AutowiredAnnotationBeanPostProcessor"

					"参数:pvs=PropertyValues: length=0"
					"参数:beanName=userController"

					if (pvsToUse == null) {
						if (filteredPds == null) {
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); //得到需要进行依赖检查的属性的集合
						}
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); //真正设置属性值的方法
						if (pvsToUse == null) {
							return;
						}
				......
		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs); //8.将所有PropertyValues中的属性填充到bean中 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; pvs=PropertyValues: length=0; beanName=userController; bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29]; 
		}
	}

}

代码块21:postProcessProperties

使用自动装配元数据,执行依赖注入

参数:pvs=PropertyValues: length=0

参数:beanName=userController

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { //pvs=PropertyValues: length=0;beanName=userController;
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); //1.在指定Bean中查找使用@Autowire注解的元数据 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
		try {

"***********"metadata.inject(bean, beanName, pvs); //2.InjectionMetadata: 执行inject()方法,开始执行属性注入或方法注入 	pvs=PropertyValues: length=0; beanName=userController;

			"(21) 使用自动装配元数据,执行依赖注入"

			"参数:beanName=userController"
			"参数:pvs=PropertyValues: length=0"

		}
		catch (BeanCreationException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
		}
		return pvs; // 	PropertyValues: length=0; 
	}

}

代码块22:inject

注入

参数:beanName=userController

参数:pvs=PropertyValues: length=0

package org.springframework.beans.factory.annotation;

public class InjectionMetadata {

	public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { //beanName=userController;pvs=PropertyValues: length=0;
		Collection<InjectedElement> checkedElements = this.checkedElements; //获取对象中加了@Autowired注解的元数据集合 	checkedElements=AutowiredFieldElement for private com.helloworld.service.UserService com.helloworld.controller.UserController.userService,; 
		Collection<InjectedElement> elementsToIterate = // 	elementsToIterate=AutowiredFieldElement for private com.helloworld.service.UserService com.helloworld.controller.UserController.userService,; 
				(checkedElements != null ? checkedElements : this.injectedElements);
		if (!elementsToIterate.isEmpty()) { // 	elementsToIterate=AutowiredFieldElement for private com.helloworld.service.UserService com.helloworld.controller.UserController.userService,; 
			for (InjectedElement element : elementsToIterate) {
				if (logger.isTraceEnabled()) { //1. 循环 PropertySources
					logger.trace("Processing injected element of bean '" + beanName + "': " + element);
				}

"***************"element.inject(target, beanName, pvs); //这两个类继承InjectionMetadata.InjectedElement,各自重写了inject方法。 	pvs=PropertyValues: length=0; beanName=userController;

				"(22) 注入"

				"参数:beanName=userController"
				"参数:pvs=PropertyValues: length=0"

			}
		}
	}

}

代码块23:inject

首先进行依赖分析

参数:beanName=userController

参数:pvs=PropertyValues: length=0

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

		@Override
		protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { //beanName=userController;pvs=PropertyValues: length=0;
			Field field = (Field) this.member; //1.拿到该元数据的属性值 	field=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService; 
			Object value;
				......
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required); //3.将field封装成DependencyDescriptor 	desc=field 'userService'; 
				desc.setContainingClass(bean.getClass()); //设置包含这个依赖的bean的class
				Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
				Assert.state(beanFactory != null, "No BeanFactory available"); //如果 beanFactory 为 null,抛出异常
				TypeConverter typeConverter = beanFactory.getTypeConverter(); //根据接口定位到实现类的过程发生此处
				try {

"*******************"value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); //4.解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中

					"(23) 首先进行依赖分析"

					"参数:descriptor=field 'userService'"
					"参数:requestingBeanName=userController"

				}
				catch (BeansException ex) {
					throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
				}
				synchronized (this) { //双重锁 懒加载
					if (!this.cached) {
						if (value != null || this.required) { //5.value不为空或者required为true
							this.cachedFieldValue = desc; //6.如果属性依赖注入的bean不止一个(Array,Collection,Map),缓存cachedFieldValue放的是DependencyDescriptor 	this.cachedFieldValue=field 'userService'; 
				......
				ReflectionUtils.makeAccessible(field); //12.设置字段访问性 	field=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService; 
				field.set(bean, value); //13.通过反射为属性赋值,将解析出来的bean实例赋值给field
			}
		}

}

代码块24:resolveDependency

依赖分析

参数:descriptor=field ‘userService’

参数:requestingBeanName=userController

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	@Nullable
	public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, //descriptor=field 'userService';requestingBeanName=userController;
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
				......
			return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName); //javaxInjectProviderClass类注入的特殊处理
		}
		else {
			Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
			if (result == null) {

"***************"result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); //4.2 解析依赖关系,返回的result为创建好的依赖对象的bean实例

				"(24) 依赖分析"

				"参数:descriptor=field 'userService'"
				"参数:beanName=userController"

			}
			return result;
		}
	}

}

代码块25:doResolveDependency

查找自动装配候选属性

参数:descriptor=field ‘userService’

参数:beanName=userController

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, //descriptor=field 'userService';beanName=userController;
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

				......

			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); //5.解析MultipleBean(下文的MultipleBean都是指类型为:Array、Collection、Map)
			if (multipleBeans != null) {
				return multipleBeans; //5.1 如果确实是容器类型的属性,则直接返回解析结果
			}


"***********"Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); //6.查找与所需类型匹配的Bean实例(matchingBeans,key:beanName;value:匹配的bean实例,或者匹配的bean实例的类型) 	matchingBeans=userServiceImpl=class com.helloworld.service.impl.UserServiceImpl;;

			"(25) 查找自动装配候选属性,第二个参数type,即是需要找到的自动装配候选者的类型com.helloworld.service.UserService。"

			"参数:beanName=userController"
			"参数:requiredType=interface com.helloworld.service.UserService"
			"参数:descriptor=field 'userService'"

			if (matchingBeans.isEmpty()) {
				if (isRequired(descriptor)) { //6.1 如果require属性为true,而找到的匹配Bean却为空则抛出异常
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); //必须则抛出NoSuchBeanDefinitionException异常
				}
				return null;
			}

			String autowiredBeanName; //定义用于存储唯一的候选Bean名变量
				......
		finally {
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); //11.执行结束,将注入点修改成原来的注入点
		}
	}

}

代码块26:findAutowireCandidates

根据类型获取候选属性名称

参数:beanName=userController

参数:requiredType=interface com.helloworld.service.UserService

参数:descriptor=field ‘userService’

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected Map<String, Object> findAutowireCandidates( //beanName=userController;requiredType=interface com.helloworld.service.UserService;descriptor=field 'userService';
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {


"*******"String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( // 	candidateNames=userServiceImpl,;

		"(26) 根据类型获取候选属性名称"

		"参数:lbf=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"
		"参数:type=interface com.helloworld.service.UserService"
		"参数:includeNonSingletons=true"
		"参数:allowEagerInit=true"

				this, requiredType, true, descriptor.isEager());
		Map<String, Object> result = new LinkedHashMap<>(candidateNames.length); //存放结果的Map(beanName -> bena实例)  最终会return的
		for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
			Class<?> autowiringType = classObjectEntry.getKey(); // 	autowiringType=interface org.springframework.beans.factory.BeanFactory; autowiringType=interface org.springframework.core.io.ResourceLoader; autowiringType=interface org.springframework.context.ApplicationContext; autowiringType=interface org.springframework.context.ApplicationEventPublisher; 
			if (autowiringType.isAssignableFrom(requiredType)) { //2.1 autowiringType是否与requiredType相同,或者是requiredType的超类、超接口
				Object autowiringValue = classObjectEntry.getValue(); //是resolvableDependencies中的子类所存的对象
				autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType); //2.3 根据给定的所需类型解析给定的自动装配值
				if (requiredType.isInstance(autowiringValue)) {
				......
			}
		}
		return result; // 	userServiceImpl=class com.helloworld.service.impl.UserServiceImpl;; 
	}

}

代码块27:beanNamesForTypeIncludingAncestors

根据类型获取候选项名称userService

参数:lbf=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.c…

参数:type=interface com.helloworld.service.UserService

参数:includeNonSingletons=true

参数:allowEagerInit=true

package org.springframework.beans.factory;

public class BeanFactoryUtils {

	public static String[] beanNamesForTypeIncludingAncestors( //lbf=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;type=interface com.helloworld.service.UserService;includeNonSingletons=true;allowEagerInit=true;
			ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {

		Assert.notNull(lbf, "ListableBeanFactory must not be null"); //断言上下文对象不能为null 	lbf=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

"*******"String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); //通过ListableBeanFactory的getBeanNamesForType方法来获取类型匹配的beanName列表 	result=userServiceImpl,;

		"(27) 根据类型获取候选项名称userService"

		"参数:type=interface com.helloworld.service.UserService"
		"参数:includeNonSingletons=true"
		"参数:allowEagerInit=true"

		if (lbf instanceof HierarchicalBeanFactory) {
			HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; //强制转化成HierarchicalBeanFactory(有分层的bean工厂)接口的实例 	hbf=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 
			if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
				String[] parentResult = beanNamesForTypeIncludingAncestors(
						(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
				result = mergeNamesWithParent(result, parentResult, hbf); //组合当前结果和父bean工厂的结果
			}
		}
		return result; // 	userServiceImpl,; 
	}

}

代码块28:getBeanNamesForType

根据类型获取候选项名称userService

参数:type=interface com.helloworld.service.UserService

参数:includeNonSingletons=true

参数:allowEagerInit=true

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { //type=interface com.helloworld.service.UserService;includeNonSingletons=true;allowEagerInit=true;
		if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
			return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit); //不可用缓存、类型无效、不允许提前加载初始化需要获取当前type的原始类型,继续获取数据
				......
		Map<Class<?>, String[]> cache =
				(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
		String[] resolvedBeanNames = cache.get(type);
		if (resolvedBeanNames != null) {
			return resolvedBeanNames;
		}

"*******"resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true); //如果缓存中没有获取到,那么只能重新获取,获取到之后就存入缓存 	resolvedBeanNames=userServiceImpl,;

		"(28) 根据类型获取候选项名称userService"

		"参数:includeNonSingletons=true"
		"参数:allowEagerInit=true"

		if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) { // 	type=interface com.helloworld.service.UserService; 
			cache.put(type, resolvedBeanNames); //放入到缓存中,解析一次以后从缓存中获取这里对应到我们这里 key是FactoryBeanService Value是beanFactoryLearn 	type=interface com.helloworld.service.UserService; resolvedBeanNames=userServiceImpl,; 
		}
		return resolvedBeanNames; // 	userServiceImpl,; 
	}

}

代码块29:doGetBeanNamesForType

根据类型匹配beanName

参数:includeNonSingletons=true

参数:allowEagerInit=true

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { //includeNonSingletons=true;allowEagerInit=true;
		List<String> result = new ArrayList<>(); //这个list集合保存类型对应的BeanNames

		// Check all bean definitions.
				......
						BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); //Check decorated bean definition, if any: We assume it'll be easierto determine the decorated bean's type than the proxy's type.这个地方是获取最原始的BeanDefinition 不是组装之后的 RootBeanDefinition
						boolean matchFound = // 	matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=true; matchFound=false; matchFound=false; 
								(allowEagerInit || !isFactoryBean ||
										(dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) &&
								(includeNonSingletons ||
										(dbd != null ? mbd.isSingleton() : isSingleton(beanName))) &&

"*******************************"isTypeMatch(beanName, type);

								"(29) 循环所有的bean定义,根据类型匹配beanName"

						if (!matchFound && isFactoryBean) {
							// In case of FactoryBean, try to match FactoryBean instance itself next.
							beanName = FACTORY_BEAN_PREFIX + beanName; //In case of FactoryBean, try to match FactoryBean instance itself next.这里讲beanName变为&beanName
							matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type); //继续判断类型匹配不匹配
						}
						if (matchFound) {
							result.add(beanName); //添加到结果 	beanName=userServiceImpl; 
						}
				......
		}

		return StringUtils.toStringArray(result); //返回所有工厂Bean 	userServiceImpl,; 
	}

}

总结:

断点三:根据元数据生成bean名称userService

  1. DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
  3. AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
  4. AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
  5. DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
  6. AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
  7. AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
  8. DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
  9. AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
  10. AbstractAutowireCapableBeanFactory.doCreateBean()————populateBean(beanName, mbd, instanceWrapper);
  11. AbstractAutowireCapableBeanFactory.populateBean()————PropertyValues pvsToUse = ibp.postProcessPropertie…
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()————metadata.inject(bean, beanName, pvs);
  13. InjectionMetadata.inject()————element.inject(target, beanName, pvs);
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()————value = beanFactory.resolveDependency(desc, beanNa…
  15. DefaultListableBeanFactory.resolveDependency()————result = doResolveDependency(descriptor, requestin…
  16. DefaultListableBeanFactory.doResolveDependency()————Map<String, Object> matchingBeans = findAutowireCa…
  17. DefaultListableBeanFactory.findAutowireCandidates()————String[] candidateNames = BeanFactoryUtils.beanNam…
  18. BeanFactoryUtils.beanNamesForTypeIncludingAncestors()————String[] result = lbf.getBeanNamesForType(type, in…
  19. DefaultListableBeanFactory.getBeanNamesForType()————resolvedBeanNames = doGetBeanNamesForType(Resolvab…
  20. DefaultListableBeanFactory.doGetBeanNamesForType()————isTypeMatch(beanName, type);

断点四:根据beanName查找创建userService对象

代码块30:doResolveDependency

获取beanName之后,回到doResolveDependency方法,生成候选组件userServiceImpl对象

参数:descriptor=field ‘userService’

参数:beanName=userController

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, //descriptor=field 'userService';beanName=userController;
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

				......
"***********"Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); //6.查找与所需类型匹配的Bean实例(matchingBeans,key:beanName;value:匹配的bean实例,或者匹配的bean实例的类型) 	matchingBeans=userServiceImpl=class com.helloworld.service.impl.UserServiceImpl;;
			"(25)"

			}

			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(autowiredBeanName); //9.将依赖的beanName加到autowiredBeanNames中 	autowiredBeanName=userServiceImpl; 
			}
			if (instanceCandidate instanceof Class) {

"***************"instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); //该方法里面调用beanFactory.getBean(beanName)实例化

				"(30) 获取beanName之后,回到doResolveDependency方法,生成候选组件userServiceImpl对象"

				"参数:beanName=userServiceImpl"
				"参数:requiredType=interface com.helloworld.service.UserService"
				"参数:beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"

			}
			Object result = instanceCandidate; //赋值给result,返回result
			if (result instanceof NullBean) {
				if (isRequired(descriptor)) { //6.1 如果require属性为true,而找到的匹配Bean却为空则抛出异常
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); //必须则抛出NoSuchBeanDefinitionException异常
				}
				result = null;
			}
				......
		finally {
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); //11.执行结束,将注入点修改成原来的注入点
		}
	}

}

代码块31:resolveCandidate

获取Bean

参数:beanName=userServiceImpl

参数:requiredType=interface com.helloworld.service.UserService

参数:beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springfra…

package org.springframework.beans.factory.config;

public class DependencyDescriptor extends InjectionPoint implements Serializable{

	public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) //beanName=userServiceImpl;requiredType=interface com.helloworld.service.UserService;beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;
			throws BeansException {


"*******"return beanFactory.getBean(beanName); //直接从容器中获取真正的对象

		"(31) 获取Bean"

		"参数:name=userServiceImpl"

	}

}

代码块32:getBean

根据beanName获取userService对象

参数:name=userServiceImpl

package org.springframework.beans.factory.support;

public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{

	@Override
	public Object getBean(String name) throws BeansException { //name=userServiceImpl;

"*******"return doGetBean(name, null, null, false); //获取name对应的bean实例,如果不存在,则创建一个

		"(32) 根据beanName获取userService对象,具体的获取过程是另外的主线,执行完这句,拿到userService对象"

	}

}

总结:

断点四:根据beanName查找创建userService对象

  1. DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
  3. AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
  4. AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
  5. DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
  6. AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
  7. AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
  8. DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
  9. AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
  10. AbstractAutowireCapableBeanFactory.doCreateBean()————populateBean(beanName, mbd, instanceWrapper);
  11. AbstractAutowireCapableBeanFactory.populateBean()————PropertyValues pvsToUse = ibp.postProcessPropertie…
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()————metadata.inject(bean, beanName, pvs);
  13. InjectionMetadata.inject()————element.inject(target, beanName, pvs);
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()————value = beanFactory.resolveDependency(desc, beanNa…
  15. DefaultListableBeanFactory.resolveDependency()————result = doResolveDependency(descriptor, requestin…
  16. DefaultListableBeanFactory.doResolveDependency()————instanceCandidate = descriptor.resolveCandidate(au…
  17. DependencyDescriptor.resolveCandidate()————return beanFactory.getBean(beanName);
  18. AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);

断点五:userController和userService均创建完毕,执行依赖注入

代码块33:inject

回到inject方法,此时userController对象和userService对象均已经创建完毕,反射的方式执行属性注入

参数:beanName=userController

参数:pvs=PropertyValues: length=0

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

		@Override
		protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { //beanName=userController;pvs=PropertyValues: length=0;
			Field field = (Field) this.member; //1.拿到该元数据的属性值 	field=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService; 
			Object value;
				......
"*******************"value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); //4.解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中
					"(23)"

						this.cached = true; //11.缓存标识设为true 	this.cached=true; 
					}
				}
			}
			if (value != null) { //value 非空, 则将.替换为_, 并将value的值加上 []
				ReflectionUtils.makeAccessible(field); //12.设置字段访问性 	field=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService; 

"***************"field.set(bean, value); //13.通过反射为属性赋值,将解析出来的bean实例赋值给field

				"(33) 回到inject方法,此时userController对象和userService对象均已经创建完毕,反射的方式执行属性注入,完成@Autowired注解注入"

			}
		}

}

总结:

断点五:userController和userService均创建完毕,执行依赖注入

  1. DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
  3. AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
  4. AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
  5. DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
  6. AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
  7. AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
  8. DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
  9. AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
  10. AbstractAutowireCapableBeanFactory.doCreateBean()————populateBean(beanName, mbd, instanceWrapper);
  11. AbstractAutowireCapableBeanFactory.populateBean()————PropertyValues pvsToUse = ibp.postProcessPropertie…
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()————metadata.inject(bean, beanName, pvs);
  13. InjectionMetadata.inject()————element.inject(target, beanName, pvs);
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()————field.set(bean, value);

附录

出现省略号的源代码全文、注释及运行时变量

完整代码:refresh

package org.springframework.context.support;

public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{

	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) { //`startupShutdownMonitor` 同步监视器用于“刷新”和“销毁”。
			// Prepare this context for refreshing.
			prepareRefresh(); //设置环境,校验参数。

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //创建BeanFactory(DefaultListableBeanFactor),加载bean定义信息。 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication]; root of factory hierarchy; 

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory); //对BeanFactory设置 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication]; root of factory hierarchy; 

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory); //4. 子类覆盖方法做额外的处理 :: 当前为空实现。 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication]; root of factory hierarchy; 

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory); //5. 执行BeanFactory各种PostProcessor处理器 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory); //6. 注册拦截bean创建的 bean处理器,这里只是注册,真正调用是在getBean的时候。 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

				// Initialize message source for this context.
				initMessageSource(); //7. 初始化上下文Message源,即不同语言的消息体(i18n)

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster(); //8. 初始化应用事件广播

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners(); //10. 在所有注册bean中查找Listener bean,并注册到广播器中

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory); //11. 初始化剩下的 (non-lazy-init) 单例. 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

				// Last step: publish corresponding event.
				finishRefresh(); //12. 最后:完成刷新过程,通知生命周期处理器LifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) { //若mock的值以force开头,则进行强制降级处理
					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); //applicationContext是否已经激活的标志,设置为false

				// 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(); //Reset common introspection caches in Spring's core, since wemight not ever need metadata for singleton beans anymore...从我们开始,重置Spring核心中的常见内省缓存可能再也不需要单例bean的元数据......
			}
		}
	}

}

完整代码:finishBeanFactoryInitialization

package org.springframework.context.support;

public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{

	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { //beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;
		// Initialize conversion service for this context.
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

		// Register a default embedded value resolver if no bean post-processor
		// (such as a PropertyPlaceholderConfigurer bean) registered any before:
		// at this point, primarily for resolution in annotation attribute values.
		if (!beanFactory.hasEmbeddedValueResolver()) { //2.如果beanFactory之前没有注册嵌入值解析器,则注册默认的嵌入值解析器:主要用于注解属性值的解析。 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); //添加嵌入式值解析器,用于解析注解属性的值
		}

		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); //3.初始化LoadTimeWeaverAware Bean实例对象 	weaverAwareNames=[]; 
		for (String weaverAwareName : weaverAwareNames) {
			getBean(weaverAwareName); //getBean方法,就相当于实例化Bean对象了
		}

		// Stop using the temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(null); //停止使用临时类加载器进行类型匹配

		// Allow for caching all bean definition metadata, not expecting further changes.
		beanFactory.freezeConfiguration(); //4.冻结所有bean定义,注册的bean定义不会被修改或进一步后处理,因为马上要创建 Bean 实例对象了 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

		// Instantiate all remaining (non-lazy-init) singletons.
		beanFactory.preInstantiateSingletons(); //5.实例化所有剩余(非懒加载)单例对象 	beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 
	}

}

完整代码:preInstantiateSingletons

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) { //1. 循环 PropertySources
			logger.trace("Pre-instantiating singletons in " + this);
		}

		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); //Iterate over a copy to allow for init methods which in turn register new bean definitions.While this may not be part of the regular factory bootstrap, it does otherwise work fine.获取beanName列表,this.beanDefinitionNames 保存了所有的 beanNames 	beanNames=org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator,; 

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) { //7.遍历beanNames,触发所有SmartInitializingSingleton的后初始化回调 	beanName=org.springframework.context.annotation.internalConfigurationAnnotationProcessor; beanName=org.springframework.context.annotation.internalAutowiredAnnotationProcessor; beanName=org.springframework.context.annotation.internalCommonAnnotationProcessor; beanName=org.springframework.context.event.internalEventListenerProcessor; beanName=org.springframework.context.event.internalEventListenerFactory; beanName=demoApplication; beanName=testAspect; beanName=userController; beanName=myBeanPostProcessor; beanName=myBeanFactoryPostProcessor; beanName=userServiceImpl; beanName=user_zhangsan; beanName=org.springframework.aop.config.internalAutoProxyCreator; 
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //3.获取beanName对应的MergedBeanDefinition 	bd=Root bean: class [org.springframework.context.annotation.ConfigurationClassPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [org.springframework.context.annotation.CommonAnnotationBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [org.springframework.context.event.EventListenerMethodProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [org.springframework.context.event.DefaultEventListenerFactory]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$9e483122]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [com.helloworld.aop.TestAspect]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\aop\TestAspect.class]; bd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; bd=Root bean: class [com.helloworld.postprocessor.bean.MyBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\postprocessor\bean\MyBeanPostProcessor.class]; bd=Root bean: class [com.helloworld.postprocessor.beanfactory.MyBeanFactoryPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\postprocessor\beanfactory\MyBeanFactoryPostProcessor.class]; bd=Root bean: class [com.helloworld.service.impl.UserServiceImpl]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\service\impl\UserServiceImpl.class]; bd=Root bean: class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //4.bd对应的Bean实例:不是抽象类 && 是单例 && 不是懒加载 	bd=Root bean: class [org.springframework.context.annotation.ConfigurationClassPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [org.springframework.context.annotation.CommonAnnotationBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [org.springframework.context.event.EventListenerMethodProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [org.springframework.context.event.DefaultEventListenerFactory]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$9e483122]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; bd=Root bean: class [com.helloworld.aop.TestAspect]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\aop\TestAspect.class]; bd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; bd=Root bean: class [com.helloworld.postprocessor.bean.MyBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\postprocessor\bean\MyBeanPostProcessor.class]; bd=Root bean: class [com.helloworld.postprocessor.beanfactory.MyBeanFactoryPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\postprocessor\beanfactory\MyBeanFactoryPostProcessor.class]; bd=Root bean: class [com.helloworld.service.impl.UserServiceImpl]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\service\impl\UserServiceImpl.class]; bd=Root bean: class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
				if (isFactoryBean(beanName)) { //5.判断beanName对应的bean是否为FactoryBean
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); //?如果是?factoryBean,则?加上?&,先创建工厂?bean?
					if (bean instanceof FactoryBean) {
						final FactoryBean<?> factory = (FactoryBean<?>) bean; //强转
						boolean isEagerInit; //5.2 判断这个FactoryBean是否希望急切的初始化
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
							isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
											((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
						if (isEagerInit) {
							getBean(beanName); //6.如果beanName对应的bean不是FactoryBean,只是普通Bean,通过beanName获取bean实例
						}
					}
				}
				else {
					getBean(beanName); //6.如果beanName对应的bean不是FactoryBean,只是普通Bean,通过beanName获取bean实例 	beanName=org.springframework.context.annotation.internalConfigurationAnnotationProcessor; beanName=org.springframework.context.annotation.internalAutowiredAnnotationProcessor; beanName=org.springframework.context.annotation.internalCommonAnnotationProcessor; beanName=org.springframework.context.event.internalEventListenerProcessor; beanName=org.springframework.context.event.internalEventListenerFactory; beanName=demoApplication; beanName=testAspect; beanName=userController; beanName=myBeanPostProcessor; beanName=myBeanFactoryPostProcessor; beanName=userServiceImpl; beanName=user_zhangsan; beanName=org.springframework.aop.config.internalAutoProxyCreator; 
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) { //7.遍历beanNames,触发所有SmartInitializingSingleton的后初始化回调 	beanName=org.springframework.context.annotation.internalConfigurationAnnotationProcessor; beanName=org.springframework.context.annotation.internalAutowiredAnnotationProcessor; beanName=org.springframework.context.annotation.internalCommonAnnotationProcessor; beanName=org.springframework.context.event.internalEventListenerProcessor; beanName=org.springframework.context.event.internalEventListenerFactory; beanName=demoApplication; beanName=testAspect; beanName=userController; beanName=myBeanPostProcessor; beanName=myBeanFactoryPostProcessor; beanName=userServiceImpl; beanName=user_zhangsan; beanName=org.springframework.aop.config.internalAutoProxyCreator; 
			Object singletonInstance = getSingleton(beanName); //7.1 拿到beanName对应的bean实例 	singletonInstance=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 
			if (singletonInstance instanceof SmartInitializingSingleton) { //7.2 判断singletonInstance是否实现了SmartInitializingSingleton接口
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; //SmartInitializingSingleton的子类
				if (System.getSecurityManager() != null) { //4.调用初始化方法
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated(); //?回调?afterSingletonsInstantiated()?方法,可以在回调中做一些事情?
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated(); //?回调?afterSingletonsInstantiated()?方法,可以在回调中做一些事情?
				}
			}
		}
	}

}

完整代码:doGetBean

package org.springframework.beans.factory.support;

public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{

	@SuppressWarnings("unchecked")
	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, //name=userController;typeCheckOnly=false;
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

		final String beanName = transformedBeanName(name); //1.解析beanName,主要是解析别名、去掉FactoryBean的前缀“&” 	beanName=userController; 
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		Object sharedInstance = getSingleton(beanName); //2.尝试从缓存中获取beanName对应的实例
		if (sharedInstance != null && args == null) {
			if (logger.isTraceEnabled()) { //1. 循环 PropertySources
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); //3.1 返回beanName对应的实例对象(主要用于FactoryBean的特殊处理,普通Bean会直接返回sharedInstance本身)
		}

		else {
			// Fail if we're already creating this bean instance:
			// We're assumably within a circular reference.
			if (isPrototypeCurrentlyInCreation(beanName)) { //例子:如果存在A中有B的属性,B中有A的属性,那么当依赖注入的时候,就会产生当A还未创建完的时候因为对于B的创建再次返回创建A,造成循环依赖
				throw new BeanCurrentlyInCreationException(beanName); //如果此时有其他线程在创建这个bean就跳过
			}

			// Check if bean definition exists in this factory.
			BeanFactory parentBeanFactory = getParentBeanFactory(); //4.没有找到则检查parentBeanFactory
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //5.1 如果parentBeanFactory存在,并且beanName在当前BeanFactory不存在Bean定义,则尝试从parentBeanFactory中获取bean实例
				// Not found -> check parent.
				String nameToLookup = originalBeanName(name); //5.2 将别名解析成真正的beanName
				if (parentBeanFactory instanceof AbstractBeanFactory) {
					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
							nameToLookup, requiredType, args, typeCheckOnly);
				}
				else if (args != null) {
					// Delegation to parent with explicit args.
					return (T) parentBeanFactory.getBean(nameToLookup, args); //委托给构造函数 getBean() 处理
				}
				else if (requiredType != null) {
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType); //交给父容器实例化对象
				}
				else {
					return (T) parentBeanFactory.getBean(nameToLookup); //没有 args,委托给标准的 getBean() 处理
				}
			}

			if (!typeCheckOnly) { //标志位。如果不是类型检查,表示要创建bean,此处在集合中做一个记录
				markBeanAsCreated(beanName); //6.如果不是仅仅做类型检测,而是创建bean实例,这里要将beanName放到alreadyCreated缓存 	beanName=userController; 
			}

			try {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //7.根据beanName重新获取MergedBeanDefinition(步骤6将MergedBeanDefinition删除了,这边获取一个新的) 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 
				checkMergedBeanDefinition(mbd, beanName, args); //7.1 检查MergedBeanDefinition 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController; 

				// Guarantee initialization of beans that the current bean depends on.
				String[] dependsOn = mbd.getDependsOn(); //8.拿到当前bean依赖的bean名称集合,在实例化自己之前,需要先实例化自己依赖的bean
				if (dependsOn != null) {
					for (String dep : dependsOn) { //8.1 遍历当前bean依赖的bean名称集合
						if (isDependent(beanName, dep)) { //8.2 检查dep是否依赖于beanName,即检查是否存在循环依赖
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
						}
						registerDependentBean(dep, beanName); //8.4 将dep和beanName的依赖关系注册到缓存中
						try {
							getBean(dep);
						}
						catch (NoSuchBeanDefinitionException ex) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
						}
					}
				}

				// Create bean instance.
				if (mbd.isSingleton()) { //9.针对不同的scope进行bean的创建 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args); //9.3.4 创建bean实例
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							destroySingleton(beanName); //2.从单例缓存中删除该beanName对应的bean(如果有的话)
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); //9.1.2 返回beanName对应的实例对象
				}

				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null; //9.2 scope为prototype的bean创建
					try {
						beforePrototypeCreation(beanName); //9.3.3 创建实例前的操作(将beanName保存到prototypesCurrentlyInCreation缓存中)
						prototypeInstance = createBean(beanName, mbd, args); //9.2.2 创建Bean实例
					}
					finally {
						afterPrototypeCreation(beanName); //9.3.5 创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除)
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); //9.2.4 返回beanName对应的实例对象
				}

				else {
					String scopeName = mbd.getScope(); //9.3.1 根据scopeName,从缓存拿到scope实例
					final Scope scope = this.scopes.get(scopeName); //指定scope上实例化bean
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); //scope属性不能接收空值
					}
					try {
						Object scopedInstance = scope.get(beanName, () -> {
							beforePrototypeCreation(beanName); //9.3.3 创建实例前的操作(将beanName保存到prototypesCurrentlyInCreation缓存中)
							try {
								return createBean(beanName, mbd, args); //9.3.4 创建bean实例
							}
							finally {
								afterPrototypeCreation(beanName); //9.3.5 创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除)
							}
						});
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); //9.3.6 返回beanName对应的实例对象
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; consider " +
								"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName); //如果创建bean实例过程中出现异常,则将beanName从alreadyCreated缓存中移除
				throw ex;
			}
		}

		// Check if required type matches the type of the actual bean instance.
		if (requiredType != null && !requiredType.isInstance(bean)) {
			try {
				T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); //10.1 类型不对,则尝试转换bean类型
				if (convertedBean == null) {
					throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); //转换不成功,抛出异常
				}
				return convertedBean;
			}
			catch (TypeMismatchException ex) {
				if (logger.isTraceEnabled()) { //1. 循环 PropertySources
					logger.trace("Failed to convert bean '" + name + "' to required type '" +
							ClassUtils.getQualifiedName(requiredType) + "'", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); //转换不成功,抛出异常
			}
		}
		return (T) bean; //11.返回创建出来的bean实例对象
	}

}

完整代码:getSingleton

package org.springframework.beans.factory.support;

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry{

	public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { //beanName=userController;
		Assert.notNull(beanName, "Bean name must not be null"); //beanName的非空判断,为空抛出一个运行时异常 	beanName=userController; 
		synchronized (this.singletonObjects) { //1.加锁,避免重复创建单例对象
			Object singletonObject = this.singletonObjects.get(beanName); //2.首先检查beanName对应的bean实例是否在缓存中存在,如果已经存在,则直接返回
			if (singletonObject == null) { //检查是否存在此单例对象
				if (this.singletonsCurrentlyInDestruction) { //3.beanName对应的bean实例不存在于缓存中,则进行Bean的创建
					throw new BeanCreationNotAllowedException(beanName,
							"Singleton bean creation not allowed while singletons of this factory are in destruction " +
							"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
				}
				if (logger.isDebugEnabled()) { //如果设置了非强制,找不到则直接返回
					logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
				}
				beforeSingletonCreation(beanName); //5.创建单例前的操作 	beanName=userController; 
				boolean newSingleton = false; //首先将新的newSingleton设置为false 	newSingleton=false; 
				boolean recordSuppressedExceptions = (this.suppressedExceptions == null); //suppressedExceptions用于记录异常相关信息 	recordSuppressedExceptions=true; 
				if (recordSuppressedExceptions) {
					this.suppressedExceptions = new LinkedHashSet<>(); //创建异常列表
				}
				try {
					singletonObject = singletonFactory.getObject(); //6.执行singletonFactory的getObject方法获取bean实例
					newSingleton = true; //标记为新的单例对象 	newSingleton=true; 
				}
				catch (IllegalStateException ex) {
					// Has the singleton object implicitly appeared in the meantime ->
					// if yes, proceed with it since the exception indicates that state.
					singletonObject = this.singletonObjects.get(beanName); //单例对象是否同时隐式出现 ->如果是,则继续进行,因为异常指示该状态。
					if (singletonObject == null) { //检查是否存在此单例对象
						throw ex;
					}
				}
				catch (BeanCreationException ex) {
					if (recordSuppressedExceptions) {
						for (Exception suppressedException : this.suppressedExceptions) {
							ex.addRelatedCause(suppressedException);
						}
					}
					throw ex;
				}
				finally {
					if (recordSuppressedExceptions) {
						this.suppressedExceptions = null; //回收异常列表
					}
					afterSingletonCreation(beanName); //7.创建单例后的操作 	beanName=userController; 
				}
				if (newSingleton) {
					addSingleton(beanName, singletonObject); //8.如果是新的单例对象,将beanName和对应的bean实例添加到缓存中(singletonObjects、registeredSingletons) 	beanName=userController; 
				}
			}
			return singletonObject; //返回缓存中的实例
		}
	}

}

完整代码:createBean

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) //beanName=userController;mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];
			throws BeanCreationException {

		if (logger.isTraceEnabled()) { //1. 循环 PropertySources
			logger.trace("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd; //bean定义信息 	mbdToUse=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 

		// Make sure bean class is actually resolved at this point, and
		// clone the bean definition in case of a dynamically resolved Class
		// which cannot be stored in the shared merged bean definition.
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName); //1.解析beanName对应的Bean的类型,例如:com.joonwhee.open.demo.service.impl.UserServiceImpl 	resolvedClass=class com.helloworld.controller.UserController; 
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { //这里判断BeanDefinition只是指定了ClassName 将解析到的Class对象设置进去,以供下面实例化时直接使用
			mbdToUse = new RootBeanDefinition(mbd); //该拷贝副本取代mdb用于后续的操作
			mbdToUse.setBeanClass(resolvedClass); //并且将解析的resolvedClass赋值给拷贝的对象,使用拷贝的副本用于后续操作
		}

		// Prepare method overrides.
		try {
			mbdToUse.prepareMethodOverrides(); //2.验证及准备覆盖的方法(对override属性进行标记及验证) 	mbdToUse=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse); //3.实例化前的处理,给InstantiationAwareBeanPostProcessor一个机会返回代理对象来替代真正的bean实例,达到“短路”效果
			if (bean != null) { //4.如果bean不为空,则会跳过Spring默认的实例化过程,直接使用返回的bean
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {
			Object beanInstance = doCreateBean(beanName, mbdToUse, args); //5.创建Bean实例(真正创建Bean的方法)
			if (logger.isTraceEnabled()) { //1. 循环 PropertySources
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance; //6.返回创建的Bean实例
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			// A previously detected exception with proper bean creation context already,
			// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}

}

完整代码:doCreateBean

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) //beanName=userController;mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null; //1.新建Bean包装类
		if (mbd.isSingleton()) { //9.针对不同的scope进行bean的创建 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); //2.如果是FactoryBean,则需要先移除未完成的FactoryBean实例的缓存
		}
		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args); //3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper 	instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29]; 
		}
		final Object bean = instanceWrapper.getWrappedInstance(); //包装的实例对象
		Class<?> beanType = instanceWrapper.getWrappedClass(); //包装的实例对象的类型 	beanType=class com.helloworld.controller.UserController; 
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType; //(包可见的字段,用于缓存给定bean定义的确定类),缓存 	mbd.resolvedTargetType=class com.helloworld.controller.UserController; 
		}

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); //Autowired注解正是通过此方法实现注入类型的预解析 	beanType=class com.helloworld.controller.UserController; mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController; 
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true; //标注这个bd已经被MergedBeanDefinitionPostProcessor的后置处理器处理过那么在第二次创建Bean的时候,不会再次调用applyMergedBeanDefinitionPostProcessors 	mbd.postProcessed=true; 
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && // 	earlySingletonExposure=true; 
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) { //如果是在initializeBean(..)过程中对前面实例化的对象作了改变,那么此时这个提前暴露出去的对象还被别的对象注入过了的话就会导致不保证单例对象的唯一性了,这里就是负责检查这种情况存在的,如果存在这种情况,可以通过getBeanNamesOfType 的allowEagerInit设置为false强制不使用earlyExposed的单例对象。
			if (logger.isTraceEnabled()) { //1. 循环 PropertySources
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); //提前将创建的 bean 实例加入到ectFactory 中这里是为了后期避免循环依赖 	beanName=userController; 
		}

		// Initialize the bean instance.
		Object exposedObject = bean; //Initialize the bean instance.  初始化bean实例。
		try {
			populateBean(beanName, mbd, instanceWrapper); //9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController; instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29]; 
			exposedObject = initializeBean(beanName, exposedObject, mbd); //10.对bean进行初始化
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) { //如果是在initializeBean(..)过程中对前面实例化的对象作了改变,那么此时这个提前暴露出去的对象还被别的对象注入过了的话就会导致不保证单例对象的唯一性了,这里就是负责检查这种情况存在的,如果存在这种情况,可以通过getBeanNamesOfType 的allowEagerInit设置为false强制不使用earlyExposed的单例对象。
			Object earlySingletonReference = getSingleton(beanName, false); //11.如果允许提前曝光实例,则进行循环依赖检查
			if (earlySingletonReference != null) { //11.1 earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference; //11.2 如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName); //11.4 拿到依赖当前bean的所有bean的beanName数组
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { //11.5 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据
							actualDependentBeans.add(dependentBean); //11.6 移除失败的添加到 actualDependentBeans
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd); //12.注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; beanName=userController; 
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject; //4.返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身
	}

}

完整代码:findAutowiringMetadata

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { //beanName=userController;clazz=class com.helloworld.controller.UserController;
		// Fall back to class name as cache key, for backwards compatibility with custom callers.
		String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); //1.设置cacheKey的值(beanName 或者 className) 	cacheKey=userController; 
		// Quick check on the concurrent map first, with minimal locking.
		InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); //2.检查beanName对应的InjectionMetadata是否已经存在于缓存中
		if (InjectionMetadata.needsRefresh(metadata, clazz)) { //5.加锁后,再次检查InjectionMetadata是否需要刷新 	clazz=class com.helloworld.controller.UserController; 
			synchronized (this.injectionMetadataCache) {
				metadata = this.injectionMetadataCache.get(cacheKey); //4.加锁后,再次从缓存中获取beanName对应的InjectionMetadata
				if (InjectionMetadata.needsRefresh(metadata, clazz)) { //5.加锁后,再次检查InjectionMetadata是否需要刷新 	clazz=class com.helloworld.controller.UserController; 
					if (metadata != null) { //pvs是null前面写的传null
						metadata.clear(pvs); //6.如果需要刷新,并且metadata不为空,则先移除
					}
					metadata = buildAutowiringMetadata(clazz); //这里的元素包括AutowiredFieldElement和AutowiredMethodElement) 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
					this.injectionMetadataCache.put(cacheKey, metadata); //8.将解析的元数据放到injectionMetadataCache缓存,以备复用,每一个类只解析一次 	cacheKey=userController; metadata=org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
				}
			}
		}
		return metadata; //返回解析的作用域元信息对象 	org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
	}

}

完整代码:buildAutowiringMetadata

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) { //clazz=class com.helloworld.controller.UserController;
		List<InjectionMetadata.InjectedElement> elements = new ArrayList<>(); //存放所有需要注入的元数据列表
		Class<?> targetClass = clazz; //目标类 	targetClass=class com.helloworld.controller.UserController; 

		do {
			final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>(); //保存完成注解解析的元素

			ReflectionUtils.doWithLocalFields(targetClass, field -> { // 	targetClass=class com.helloworld.controller.UserController; 
				AnnotationAttributes ann = findAutowiredAnnotation(field); //2.2.1 获取field上的@Autowired注解信息
				if (ann != null) { //8.如果该候选者使用了@Autowire注解
					if (Modifier.isStatic(field.getModifiers())) { //2.2.2 校验field是否被static修饰,如果是则直接返回,因为@Autowired注解不支持static修饰的field
						if (logger.isInfoEnabled()) { //invoker 可用性检查
							logger.info("Autowired annotation is not supported on static fields: " + field);
						}
						return;
					}
					boolean required = determineRequiredStatus(ann); //2.3.6 获取@Autowired注解的required的属性值
					currElements.add(new AutowiredFieldElement(field, required)); //2.2.4 将field、required封装成AutowiredFieldElement,添加到currElements
				}
			});

			ReflectionUtils.doWithLocalMethods(targetClass, method -> { // 	targetClass=class com.helloworld.controller.UserController; 
				Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); //2.3.1 找到桥接方法
				if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { //2.3.2 判断方法的可见性,如果不可见则直接返回
					return;
				}
				AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod); //2.3.3 获取method上的@Autowired注解信息
				if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
					if (Modifier.isStatic(method.getModifiers())) { //2.3.4 校验method是否被static修饰,如果是则直接返回,因为@Autowired注解不支持static修饰的method
						if (logger.isInfoEnabled()) { //invoker 可用性检查
							logger.info("Autowired annotation is not supported on static methods: " + method);
						}
						return;
					}
					if (method.getParameterCount() == 0) {
						if (logger.isInfoEnabled()) { //invoker 可用性检查
							logger.info("Autowired annotation should only be used on methods with parameters: " +
									method);
						}
					}
					boolean required = determineRequiredStatus(ann); //2.3.6 获取@Autowired注解的required的属性值
					PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); //2.3.7  获取method的属性描述器
					currElements.add(new AutowiredMethodElement(method, required, pd)); //2.3.8 将method、required、pd封装成AutowiredMethodElement,添加到currElements
				}
			});

			elements.addAll(0, currElements); //2.4 将本次循环获取到的注解信息添加到elements 	currElements=AutowiredFieldElement for private com.helloworld.service.UserService com.helloworld.controller.UserController.userService,; 
			targetClass = targetClass.getSuperclass(); //2.5 在解析完targetClass之后,递归解析父类,将所有的@Autowired的属性和方法收集起来,且类的层级越高其属性会被越优先注入 	targetClass=class java.lang.Object; 
		}
		while (targetClass != null && targetClass != Object.class);

		return new InjectionMetadata(clazz, elements); //2.7 将clazz和解析到的注入的元素封装成InjectionMetadata 	org.springframework.beans.factory.annotation.InjectionMetadata@58a9760d; 
	}

}

完整代码:populateBean

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	@SuppressWarnings("deprecation")  // for postProcessPropertyValues
	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { //beanName=userController;mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class];bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29];
		if (bw == null) { //2.bw为空时的处理
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}

		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		boolean continueWithPropertyPopulation = true; //用于标识是否继续之后的属性填充 	continueWithPropertyPopulation=true; 

		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //1.mbd不是合成的,并且BeanFactory中存在InstantiationAwareBeanPostProcessor 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; 
			for (BeanPostProcessor bp : getBeanPostProcessors()) { //7.1 应用后置处理器InstantiationAwareBeanPostProcessor 	bp=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 
				if (bp instanceof InstantiationAwareBeanPostProcessor) { //2.应用InstantiationAwareBeanPostProcessor后置处理器,允许postProcessBeforeInstantiation方法返回bean对象的代理
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //应用后处理器InstantiationAwareBeanPostProcessor,调用其postProcessPropertyValues方法作用是对需要进行依赖检查的属性进行处理Autowired等注解的属性就是在这里完成注入的 	ibp=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { //3.2 在bean实例化后,属性填充之前被调用,允许修改bean的属性,如果返回false,则跳过之后的属性填充
						continueWithPropertyPopulation = false; //3.3 如果返回false,将continueWithPropertyPopulation赋值为false,代表要跳过之后的属性填充
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) { //3.4 如果continueWithPropertyPopulation为false,则跳过之后的属性填充
			return;
		}

		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); //bean 的属性值

		if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs); //封装属性列表
			// Add property values based on autowire by name if applicable.
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs); //4.1 解析autowireByName的注入
			}
			// Add property values based on autowire by type if applicable.
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs); //4.2 解析autowireByType的注入
			}
			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); //5.BeanFactory是否注册过InstantiationAwareBeanPostProcessors 	hasInstAwareBpps=true; 
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); //是否需要依赖检查,默认是不会进行依赖检查的 	needsDepCheck=false; 

		PropertyDescriptor[] filteredPds = null; //3. 注解注入:后置处理器ibp#postProcessProperties,大名鼎鼎的@Autowired就是在这处理的。
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues(); //如果为空,再次从BeanDefinition对象中获取,TODO? 	pvs=PropertyValues: length=0; 
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) { //7.1 应用后置处理器InstantiationAwareBeanPostProcessor 	bp=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 
				if (bp instanceof InstantiationAwareBeanPostProcessor) { //2.应用InstantiationAwareBeanPostProcessor后置处理器,允许postProcessBeforeInstantiation方法返回bean对象的代理
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //应用后处理器InstantiationAwareBeanPostProcessor,调用其postProcessPropertyValues方法作用是对需要进行依赖检查的属性进行处理Autowired等注解的属性就是在这里完成注入的 	ibp=proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false; 
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); //这句就是核心 	pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0; 
					if (pvsToUse == null) {
						if (filteredPds == null) {
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); //得到需要进行依赖检查的属性的集合
						}
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); //真正设置属性值的方法
						if (pvsToUse == null) {
							return;
						}
					}
					pvs = pvsToUse; // 	pvs=PropertyValues: length=0; pvs=PropertyValues: length=0; pvs=PropertyValues: length=0; pvs=PropertyValues: length=0; 
				}
			}
		}
		if (needsDepCheck) {
			if (filteredPds == null) {
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); //得到需要进行依赖检查的属性的集合
			}
			checkDependencies(beanName, mbd, filteredPds, pvs); //7.2 依赖检查,对应depends-on属性
		}

		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs); //8.将所有PropertyValues中的属性填充到bean中 	mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; pvs=PropertyValues: length=0; beanName=userController; bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29]; 
		}
	}

}

完整代码:inject

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

		@Override
		protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { //beanName=userController;pvs=PropertyValues: length=0;
			Field field = (Field) this.member; //1.拿到该元数据的属性值 	field=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService; 
			Object value;
			if (this.cached) { //2.如果缓存中已经存在,则直接从缓存中解析属性
				value = resolvedCachedArgument(beanName, this.cachedFieldValue); //第一次注入的时候肯定没有缓存这里也是对原型情况的处理
			}
			else {
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required); //3.将field封装成DependencyDescriptor 	desc=field 'userService'; 
				desc.setContainingClass(bean.getClass()); //设置包含这个依赖的bean的class
				Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
				Assert.state(beanFactory != null, "No BeanFactory available"); //如果 beanFactory 为 null,抛出异常
				TypeConverter typeConverter = beanFactory.getTypeConverter(); //根据接口定位到实现类的过程发生此处
				try {
					value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); //4.解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中
				}
				catch (BeansException ex) {
					throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
				}
				synchronized (this) { //双重锁 懒加载
					if (!this.cached) {
						if (value != null || this.required) { //5.value不为空或者required为true
							this.cachedFieldValue = desc; //6.如果属性依赖注入的bean不止一个(Array,Collection,Map),缓存cachedFieldValue放的是DependencyDescriptor 	this.cachedFieldValue=field 'userService'; 
							registerDependentBeans(beanName, autowiredBeanNames); //7.注册依赖关系到缓存(beanName 依赖 autowiredBeanNames) 	autowiredBeanNames=userServiceImpl,; beanName=userController; 
							if (autowiredBeanNames.size() == 1) { //8.如果属性依赖注入的bean只有一个(正常都是一个) 	autowiredBeanNames=userServiceImpl,; 
								String autowiredBeanName = autowiredBeanNames.iterator().next(); //自动注入的名称 	autowiredBeanName=userServiceImpl; 
								if (beanFactory.containsBean(autowiredBeanName) &&
										beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { // 	autowiredBeanName=userServiceImpl; 
									this.cachedFieldValue = new ShortcutDependencyDescriptor(
											desc, autowiredBeanName, field.getType());
								}
							}
						}
						else {
							this.cachedFieldValue = null;
						}
						this.cached = true; //11.缓存标识设为true 	this.cached=true; 
					}
				}
			}
			if (value != null) { //value 非空, 则将.替换为_, 并将value的值加上 []
				ReflectionUtils.makeAccessible(field); //12.设置字段访问性 	field=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService; 
				field.set(bean, value); //13.通过反射为属性赋值,将解析出来的bean实例赋值给field
			}
		}

}

完整代码:resolveDependency

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	@Nullable
	public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, //descriptor=field 'userService';requestingBeanName=userController;
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); //* descriptor.getDependencyType() 解析set方法,获取set方法注入属性的类型* Optional、ObjectFactory、ObjectProvider、javaxInjectProviderClass* 都是类型判断,这些类型有特殊的对象创建方式
		if (Optional.class == descriptor.getDependencyType()) {
			return createOptionalDependency(descriptor, requestingBeanName); //Optional类注入的特殊处理
		}
		else if (ObjectFactory.class == descriptor.getDependencyType() ||
				ObjectProvider.class == descriptor.getDependencyType()) {
			return new DependencyObjectProvider(descriptor, requestingBeanName); //ObjectFactory和ObjectProvider类注入的特殊处理
		}
		else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
			return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName); //javaxInjectProviderClass类注入的特殊处理
		}
		else {
			Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
			if (result == null) {
				result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); //4.2 解析依赖关系,返回的result为创建好的依赖对象的bean实例
			}
			return result;
		}
	}

}

完整代码:doResolveDependency

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, //descriptor=field 'userService';beanName=userController;
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); //1.设置当前的descriptor(存储了方法参数等信息)为当前注入点
		try {
			Object shortcut = descriptor.resolveShortcut(this); //2.如果是ShortcutDependencyDescriptor,则直接通过getBean方法获取Bean实例,并返回;否则返回null
			if (shortcut != null) {
				return shortcut; //返回快捷的解析信息
			}

			Class<?> type = descriptor.getDependencyType(); //3.拿到descriptor包装的方法的参数类型(通过参数索引定位到具体的参数) 	type=interface com.helloworld.service.UserService; 
			Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); //4.用于支持spring中新增的注解@Value(确定给定的依赖项是否声明Value注解,如果有则拿到值)
			if (value != null) { //value 非空, 则将.替换为_, 并将value的值加上 []
				if (value instanceof String) {
					String strVal = resolveEmbeddedValue((String) value); //使用StringValueResolver处理${}占位符~所以我们常用的只使用@Value("${xxx}")这样来注入值或者你就是个字面量值,到这一步就已经完事了~解析完成若你是个el表达式  或者文件资源Resource啥的,会继续交给下面的beanExpressionResolver处理,所以它是处理复杂类型的核心~
					BeanDefinition bd = (beanName != null && containsBean(beanName) ?
							getMergedBeanDefinition(beanName) : null);
					value = evaluateBeanDefinitionString(strVal, bd); //此处注意:处理器是BeanExpressionResolver~~~~它是处理@Value表达式的核心方法它的默认值是:StandardBeanExpressionResolver#evaluate这里面就会解析
				}
				TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); //若我们没有定制,此处为SimpleTypeConverter 值已经拿到手了,经由转换器以转换 就可以测地的返回喽~~~解析结束
				try {
					return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor()); //2.2 类型转换如果需要的话,
				}
				catch (UnsupportedOperationException ex) {
					// A custom TypeConverter which does not support TypeDescriptor resolution...
					return (descriptor.getField() != null ?
							converter.convertIfNecessary(value, type, descriptor.getField()) :
							converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
				}
			}

			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); //5.解析MultipleBean(下文的MultipleBean都是指类型为:Array、Collection、Map)
			if (multipleBeans != null) {
				return multipleBeans; //5.1 如果确实是容器类型的属性,则直接返回解析结果
			}

			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); //6.查找与所需类型匹配的Bean实例(matchingBeans,key:beanName;value:匹配的bean实例,或者匹配的bean实例的类型) 	matchingBeans=userServiceImpl=class com.helloworld.service.impl.UserServiceImpl;; 
			if (matchingBeans.isEmpty()) {
				if (isRequired(descriptor)) { //6.1 如果require属性为true,而找到的匹配Bean却为空则抛出异常
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); //必须则抛出NoSuchBeanDefinitionException异常
				}
				return null;
			}

			String autowiredBeanName; //定义用于存储唯一的候选Bean名变量
			Object instanceCandidate; //定义用于存储唯一的候选Bean对象变量

			if (matchingBeans.size() > 1) {
				autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); //7.1 从多个候选者中选出最优的那个
				if (autowiredBeanName == null) {
					if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
						return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans); //Autowire的required为true,且不是multipleBean,交由descriptor解析(该方法默认抛出异常)
					}
					else {
						// In case of an optional Collection/Map, silently ignore a non-unique case:
						// possibly it was meant to be an empty collection of multiple regular beans
						// (before 4.3 in particular when we didn't even look for collection beans).
						return null;
					}
				}
				instanceCandidate = matchingBeans.get(autowiredBeanName); //7.2.拿到autowiredBeanName对应的value(bean实例或bean实例类型)
			}
			else {
				// We have exactly one match.
				Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); //8.只找到了一个候选者,则直接使用该候选者
				autowiredBeanName = entry.getKey(); //让autowireBeanName引用该元素的候选bean名 	autowiredBeanName=userServiceImpl; 
				instanceCandidate = entry.getValue(); //instanceCandidate可以是已经实例化的对象,也可以是对应类型的class对象 	instanceCandidate=class com.helloworld.service.impl.UserServiceImpl; 
			}

			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(autowiredBeanName); //9.将依赖的beanName加到autowiredBeanNames中 	autowiredBeanName=userServiceImpl; 
			}
			if (instanceCandidate instanceof Class) {
				instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); //该方法里面调用beanFactory.getBean(beanName)实例化
			}
			Object result = instanceCandidate; //赋值给result,返回result
			if (result instanceof NullBean) {
				if (isRequired(descriptor)) { //6.1 如果require属性为true,而找到的匹配Bean却为空则抛出异常
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); //必须则抛出NoSuchBeanDefinitionException异常
				}
				result = null;
			}
			if (!ClassUtils.isAssignableValue(type, result)) {
				throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass()); //抛出Bean不是必需类型异常
			}
			return result;
		}
		finally {
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); //11.执行结束,将注入点修改成原来的注入点
		}
	}

}

完整代码:findAutowireCandidates

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected Map<String, Object> findAutowireCandidates( //beanName=userController;requiredType=interface com.helloworld.service.UserService;descriptor=field 'userService';
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {

		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( // 	candidateNames=userServiceImpl,; 
				this, requiredType, true, descriptor.isEager());
		Map<String, Object> result = new LinkedHashMap<>(candidateNames.length); //存放结果的Map(beanName -> bena实例)  最终会return的
		for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
			Class<?> autowiringType = classObjectEntry.getKey(); // 	autowiringType=interface org.springframework.beans.factory.BeanFactory; autowiringType=interface org.springframework.core.io.ResourceLoader; autowiringType=interface org.springframework.context.ApplicationContext; autowiringType=interface org.springframework.context.ApplicationEventPublisher; 
			if (autowiringType.isAssignableFrom(requiredType)) { //2.1 autowiringType是否与requiredType相同,或者是requiredType的超类、超接口
				Object autowiringValue = classObjectEntry.getValue(); //是resolvableDependencies中的子类所存的对象
				autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType); //2.3 根据给定的所需类型解析给定的自动装配值
				if (requiredType.isInstance(autowiringValue)) {
					result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue); //2.4 将autowiringValue放到结果集中,此时的value为bean实例
					break;
				}
			}
		}
		for (String candidate : candidateNames) { //5.如果使用降级匹配结果还是空,则考虑自引用 	candidate=userServiceImpl; 
			if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { //3.1 如果不是自引用 && candidate有资格作为依赖注入的候选者 	descriptor=field 'userService'; beanName=userController; candidate=userServiceImpl; 
				addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中 	descriptor=field 'userService'; requiredType=interface com.helloworld.service.UserService; candidate=userServiceImpl; result=userServiceImpl=class com.helloworld.service.impl.UserServiceImpl;; 
			}
		}
		if (result.isEmpty()) { //如果结果为空,则返回需要更多的输入
			boolean multiple = indicatesMultipleBeans(requiredType); //如果依旧没找到,执行降级匹配
			// Consider fallback matches if the first pass failed to find anything...
			DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); //4.1 使用降级匹配(跟正常匹配类似)
			for (String candidate : candidateNames) { //5.如果使用降级匹配结果还是空,则考虑自引用
				if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
						(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
					addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中
				}
			}
			if (result.isEmpty() && !multiple) {
				// Consider self references as a final pass...
				// but in the case of a dependency collection, not the very same bean itself.
				for (String candidate : candidateNames) { //5.如果使用降级匹配结果还是空,则考虑自引用
					if (isSelfReference(beanName, candidate) &&
							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) {
						addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中
					}
				}
			}
		}
		return result; // 	userServiceImpl=class com.helloworld.service.impl.UserServiceImpl;; 
	}

}

完整代码:getBeanNamesForType

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { //type=interface com.helloworld.service.UserService;includeNonSingletons=true;allowEagerInit=true;
		if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
			return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit); //不可用缓存、类型无效、不允许提前加载初始化需要获取当前type的原始类型,继续获取数据
		}
		Map<Class<?>, String[]> cache =
				(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
		String[] resolvedBeanNames = cache.get(type);
		if (resolvedBeanNames != null) {
			return resolvedBeanNames;
		}
		resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true); //如果缓存中没有获取到,那么只能重新获取,获取到之后就存入缓存 	resolvedBeanNames=userServiceImpl,; 
		if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) { // 	type=interface com.helloworld.service.UserService; 
			cache.put(type, resolvedBeanNames); //放入到缓存中,解析一次以后从缓存中获取这里对应到我们这里 key是FactoryBeanService Value是beanFactoryLearn 	type=interface com.helloworld.service.UserService; resolvedBeanNames=userServiceImpl,; 
		}
		return resolvedBeanNames; // 	userServiceImpl,; 
	}

}

完整代码:doGetBeanNamesForType

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { //includeNonSingletons=true;allowEagerInit=true;
		List<String> result = new ArrayList<>(); //这个list集合保存类型对应的BeanNames

		// Check all bean definitions.
		for (String beanName : this.beanDefinitionNames) { // 	beanName=org.springframework.context.annotation.internalConfigurationAnnotationProcessor; beanName=org.springframework.context.annotation.internalAutowiredAnnotationProcessor; beanName=org.springframework.context.annotation.internalCommonAnnotationProcessor; beanName=org.springframework.context.event.internalEventListenerProcessor; beanName=org.springframework.context.event.internalEventListenerFactory; beanName=demoApplication; beanName=testAspect; beanName=userController; beanName=myBeanPostProcessor; beanName=myBeanFactoryPostProcessor; beanName=userServiceImpl; beanName=user_zhangsan; beanName=org.springframework.aop.config.internalAutoProxyCreator; 
			// Only consider bean as eligible if the bean name
			// is not defined as alias for some other bean.
			if (!isAlias(beanName)) { // 	beanName=org.springframework.context.annotation.internalConfigurationAnnotationProcessor; beanName=org.springframework.context.annotation.internalAutowiredAnnotationProcessor; beanName=org.springframework.context.annotation.internalCommonAnnotationProcessor; beanName=org.springframework.context.event.internalEventListenerProcessor; beanName=org.springframework.context.event.internalEventListenerFactory; beanName=demoApplication; beanName=testAspect; beanName=userController; beanName=myBeanPostProcessor; beanName=myBeanFactoryPostProcessor; beanName=userServiceImpl; beanName=user_zhangsan; beanName=org.springframework.aop.config.internalAutoProxyCreator; 
				try {
					RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //Retrieve corresponding bean definition.根据beanName重新检索BeanDefinition 这里返回一个RootBeanDefinition 如果父子容器中存在相同类型的bean会进行合并 	mbd=Root bean: class [org.springframework.context.annotation.ConfigurationClassPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [org.springframework.context.annotation.CommonAnnotationBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [org.springframework.context.event.EventListenerMethodProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [org.springframework.context.event.DefaultEventListenerFactory]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$9e483122]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [com.helloworld.aop.TestAspect]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\aop\TestAspect.class]; mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; mbd=Root bean: class [com.helloworld.postprocessor.bean.MyBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\postprocessor\bean\MyBeanPostProcessor.class]; mbd=Root bean: class [com.helloworld.postprocessor.beanfactory.MyBeanFactoryPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\postprocessor\beanfactory\MyBeanFactoryPostProcessor.class]; mbd=Root bean: class [com.helloworld.service.impl.UserServiceImpl]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\service\impl\UserServiceImpl.class]; mbd=Root bean: class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
					// Only check bean definition if it is complete.
					if (!mbd.isAbstract() && (allowEagerInit ||
							(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
									!requiresEagerInitForType(mbd.getFactoryBeanName()))) { // 	mbd=Root bean: class [org.springframework.context.annotation.ConfigurationClassPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [org.springframework.context.annotation.CommonAnnotationBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [org.springframework.context.event.EventListenerMethodProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [org.springframework.context.event.DefaultEventListenerFactory]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$9e483122]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; mbd=Root bean: class [com.helloworld.aop.TestAspect]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\aop\TestAspect.class]; mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]; mbd=Root bean: class [com.helloworld.postprocessor.bean.MyBeanPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\postprocessor\bean\MyBeanPostProcessor.class]; mbd=Root bean: class [com.helloworld.postprocessor.beanfactory.MyBeanFactoryPostProcessor]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\postprocessor\beanfactory\MyBeanFactoryPostProcessor.class]; mbd=Root bean: class [com.helloworld.service.impl.UserServiceImpl]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\service\impl\UserServiceImpl.class]; mbd=Root bean: class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
						// In case of FactoryBean, match object created by FactoryBean.
						boolean isFactoryBean = isFactoryBean(beanName, mbd); //In case of FactoryBean, match object created by FactoryBean.判断是不是FactoryBean 	isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; isFactoryBean=false; 
						BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); //Check decorated bean definition, if any: We assume it'll be easierto determine the decorated bean's type than the proxy's type.这个地方是获取最原始的BeanDefinition 不是组装之后的 RootBeanDefinition
						boolean matchFound = // 	matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=false; matchFound=true; matchFound=false; matchFound=false; 
								(allowEagerInit || !isFactoryBean ||
										(dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) &&
								(includeNonSingletons ||
										(dbd != null ? mbd.isSingleton() : isSingleton(beanName))) &&
								isTypeMatch(beanName, type);
						if (!matchFound && isFactoryBean) {
							// In case of FactoryBean, try to match FactoryBean instance itself next.
							beanName = FACTORY_BEAN_PREFIX + beanName; //In case of FactoryBean, try to match FactoryBean instance itself next.这里讲beanName变为&beanName
							matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type); //继续判断类型匹配不匹配
						}
						if (matchFound) {
							result.add(beanName); //添加到结果 	beanName=userServiceImpl; 
						}
					}
				}
				catch (CannotLoadBeanClassException ex) {
					if (allowEagerInit) {
						throw ex;
					}
					// Probably a class name with a placeholder: let's ignore it for type matching purposes.
					if (logger.isTraceEnabled()) { //1. 循环 PropertySources
						logger.trace("Ignoring bean class loading failure for bean '" + beanName + "'", ex);
					}
					onSuppressedException(ex);
				}
				catch (BeanDefinitionStoreException ex) {
					if (allowEagerInit) {
						throw ex;
					}
					// Probably some metadata with a placeholder: let's ignore it for type matching purposes.
					if (logger.isTraceEnabled()) { //1. 循环 PropertySources
						logger.trace("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex);
					}
					onSuppressedException(ex);
				}
			}
		}

		// Check manually registered singletons too.
		for (String beanName : this.manualSingletonNames) { // 	beanName=environment; beanName=systemProperties; beanName=systemEnvironment; beanName=org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry; beanName=messageSource; beanName=applicationEventMulticaster; 
			try {
				// In case of FactoryBean, match object created by FactoryBean.
				if (isFactoryBean(beanName)) { //5.判断beanName对应的bean是否为FactoryBean
					if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
						result.add(beanName); //添加到结果
						// Match found for this bean: do not match FactoryBean itself anymore.
						continue;
					}
					// In case of FactoryBean, try to match FactoryBean itself next.
					beanName = FACTORY_BEAN_PREFIX + beanName; //In case of FactoryBean, try to match FactoryBean instance itself next.这里讲beanName变为&beanName
				}
				// Match raw bean instance (might be raw FactoryBean).
				if (isTypeMatch(beanName, type)) {
					result.add(beanName); //添加到结果
				}
			}
			catch (NoSuchBeanDefinitionException ex) {
				// Shouldn't happen - probably a result of circular reference resolution...
				if (logger.isTraceEnabled()) { //1. 循环 PropertySources
					logger.trace("Failed to check manually registered singleton with name '" + beanName + "'", ex);
				}
			}
		}

		return StringUtils.toStringArray(result); //返回所有工厂Bean 	userServiceImpl,; 
	}

}

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2021-12-24 18:47:11  更:2021-12-24 18:48:11 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/18 4:38:01-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码