在线记录源码调试之@Qualifier源码分析

测试用例1

在DemoApplication中注册两个bean,用户zhangsan和用户lisi,给demoApplication对象注入zhangsan,并标注@Qualifier

@Configuration
@ComponentScan
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DemoApplication {

    @Autowired
    @Qualifier("zhangsan")
    private UserInfo userInfo;

    public static void main( String[] args ) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DemoApplication.class);
        UserInfo userInfo = (UserInfo) ctx.getBean("zhangsan");
    }

    @Bean(name = "zhangsan", initMethod = "init")
    public UserInfo getUserInfo1() {
        return new UserInfo("zhangsan");
    }

    @Bean(name = "lisi", initMethod = "init")
    public UserInfo getUserInfo2() {
        return new UserInfo("lisi");
    }
}

定位到创建bean实例demoApplication

将断点打到AbstractAutowireCapableBeanFactory.createBeanInstance方法,则代码执行过程如下

代码块1:main

构造器

参数:args=[]

package com.helloworld;

public class DemoApplication {

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

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DemoApplication.class);

        "(1) 构造器"

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

				......
    }

}

代码块2:AnnotationConfigApplicationContext()

刷新

参数: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,;
				......

		refresh();

		"(2) 刷新"

	}

}

代码块3:refresh

完成Bean工厂初始化

package org.springframework.context.support;

public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{

	@Override
	public void refresh() throws BeansException, IllegalStateException {
				......

				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,userServiceImpl,zhangsan,lisi,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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"

				"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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;"

				......
	}

}

代码块4:finishBeanFactoryInitialization

预实例化单例

参数: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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;
				......

		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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

		"(4) 预实例化单例"

		"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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;"

	}

}

代码块5:preInstantiateSingletons

获取Bean

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	public void preInstantiateSingletons() throws BeansException {
				......

					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=userServiceImpl; beanName=zhangsan; beanName=lisi; beanName=org.springframework.aop.config.internalAutoProxyCreator; 

					"(5) 获取Bean"

					"参数:name=demoApplication"

					"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=userServiceImpl; beanName=zhangsan; beanName=lisi; beanName=org.springframework.aop.config.internalAutoProxyCreator;"

				......
	}

}

代码块6:getBean

获取bean

参数:name=demoApplication

package org.springframework.beans.factory.support;

public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{

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

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

		"(6) 获取bean"

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

		"获取name对应的bean实例,如果不存在,则创建一个"

	}

}

代码块7:doGetBean

获取单例

参数:name=demoApplication

参数: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=demoApplication;typeCheckOnly=false;
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
				......

					sharedInstance = getSingleton(beanName, () -> {

					"(7) 获取单例"

					"参数:beanName=demoApplication"

				......
	}

}

代码块8:getSingleton

创建Bean

参数:beanName=demoApplication

package org.springframework.beans.factory.support;

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry{

	public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { //beanName=demoApplication;
				......

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

					"(8) 创建Bean"

					"参数:beanName=demoApplication"
					"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"

					"6.执行singletonFactory的getObject方法获取bean实例"

				......
	}

}

代码块9:createBean

创建bean

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
			throws BeanCreationException {
				......

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

			"(9) 创建bean"

			"参数:beanName=demoApplication"
			"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"

			"5.创建Bean实例(真正创建Bean的方法)"

				......
	}

}

代码块10:doCreateBean

创建Bean实例

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
			throws BeanCreationException {
				......

			instanceWrapper = createBeanInstance(beanName, mbd, args); //3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper 	instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 

			"(10) 创建Bean实例"

			"参数:beanName=demoApplication"
			"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"

			"3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper 	instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47];"

				......
	}

}

代码块11:createBeanInstance

使用默认构造器,实例化bean

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { //beanName=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
				......

		return instantiateBean(beanName, mbd); //6.没有特殊处理,则使用默认的构造函数进行bean的实例化 	org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 

		"(11) 使用默认构造器,实例化bean"

		"6.没有特殊处理,则使用默认的构造函数进行bean的实例化 	org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47];"

	}

}

小结:调用栈

定位到创建bean实例demoApplication

  1. *DemoApplication.main()
  2. *AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. *AbstractApplicationContext.refresh()
  4. *AbstractApplicationContext.finishBeanFactoryInitialization()
  5. *DefaultListableBeanFactory.preInstantiateSingletons()
  6. *AbstractBeanFactory.getBean()
  7. *AbstractBeanFactory.doGetBean()
  8. *DefaultSingletonBeanRegistry.getSingleton()
  9. *AbstractAutowireCapableBeanFactory.createBean()
  10. *AbstractAutowireCapableBeanFactory.doCreateBean()
  11. *AbstractAutowireCapableBeanFactory.createBeanInstance()

找到demoApplication的成员变量userInfo的自动装配注解及属性

将断点打到AutowiredAnnotationBeanPostProcessor.findAutowiredAnnotation方法,则代码执行过程如下

代码块12:doCreateBean

应用合并的Bean定义后处理器

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
			throws BeanCreationException {
				......
			instanceWrapper = createBeanInstance(beanName, mbd, args);
			"(10)"


					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); //Autowired注解正是通过此方法实现注入类型的预解析 	beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 

					"(12) 应用合并的Bean定义后处理器"

					"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"
					"参数:beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306"
					"参数:beanName=demoApplication"

					"Autowired注解正是通过此方法实现注入类型的预解析 	beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication;"

				......
	}

}

代码块13:applyMergedBeanDefinitionPostProcessors

后期处理合并Bean定义

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

参数:beanType=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

参数:beanName=demoApplication

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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;beanName=demoApplication;
				......

				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName); //执行postProcessMergedBeanDefinition 	beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 

				"(13) 后期处理合并Bean定义"

				"参数:beanDefinition=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"
				"参数:beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306"
				"参数:beanName=demoApplication"

				"执行postProcessMergedBeanDefinition 	beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication;"

				......
	}

}

代码块14:postProcessMergedBeanDefinition

查找@Autowired自动装配元数据

参数:beanDefinition=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abst…

参数:beanType=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

参数:beanName=demoApplication

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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;beanName=demoApplication;

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

		"(14) 查找@Autowired自动装配元数据"

		"参数:beanName=demoApplication"
		"参数:clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306"

		"1.在指定Bean中查找使用@Autowire注解的元数据 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@192d43ce;"

				......
	}

}

代码块15:findAutowiringMetadata

构建自动配置元数据

参数:beanName=demoApplication

参数:clazz=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { //beanName=demoApplication;clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;
				......

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

					"(15) 构建自动配置元数据"

					"参数:clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306"

					"这里的元素包括AutowiredFieldElement和AutowiredMethodElement) 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@192d43ce;"

				......
	}

}

代码块16:buildAutowiringMetadata

查找@Autowired注解

参数:clazz=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) { //clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;
				......

			ReflectionUtils.doWithLocalFields(targetClass, field -> { // 	targetClass=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; targetClass=class com.helloworld.DemoApplication; 

			AnnotationAttributes ann = findAutowiredAnnotation(field); //2.2.1 获取field上的@Autowired注解信息

			"(16) 查找@Autowired注解"

			"参数:ao=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo"

			"targetClass=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; targetClass=class com.helloworld.DemoApplication;"

				......
	}

}

代码块17:findAutowiredAnnotation

找到userInfo的@Autowired注解及注解属性,构建元数据

参数:ao=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	@Nullable
	private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) { //ao=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo;
				......

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

				"(17) 找到userInfo的@Autowired注解及注解属性,构建元数据"

				"3.拿到注解的合并注解属性,@Autowire在这边拿到,required=true(默认属性) 	attributes=required=true;;"

				......
	}

}

小结:调用栈

找到demoApplication的成员变量userInfo的自动装配注解及属性

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. *AbstractAutowireCapableBeanFactory.doCreateBean()
  11. *AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()
  12. *AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition()
  13. *AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata()
  14. *AutowiredAnnotationBeanPostProcessor.buildAutowiringMetadata()
  15. *AutowiredAnnotationBeanPostProcessor.findAutowiredAnnotation()

将找到的@Autowired注解元数据放入缓存

将断点打到AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata方法,则代码执行过程如下

代码块18:findAutowiringMetadata

将找到的@Autowired注解元数据放入缓存

参数:beanName=demoApplication

参数:clazz=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { //beanName=demoApplication;clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;
				......
					metadata = buildAutowiringMetadata(clazz);
					"(15)"


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

					"(18) 将找到的@Autowired注解元数据放入缓存"

					"8.将解析的元数据放到injectionMetadataCache缓存,以备复用,每一个类只解析一次 	cacheKey=demoApplication; metadata=org.springframework.beans.factory.annotation.InjectionMetadata@192d43ce;"

				......
	}

}

小结:调用栈

将找到的@Autowired注解元数据放入缓存

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()
  12. AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition()
  13. *AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata()

demoApplication的属性userInfo依赖注入

将断点打到AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject方法,则代码执行过程如下

代码块19:doCreateBean

填充Bean

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
			throws BeanCreationException {
				......
			instanceWrapper = createBeanInstance(beanName, mbd, args);
			"(10)"

					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
					"(12)"


			populateBean(beanName, mbd, instanceWrapper); //9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例 	mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 

			"(19) 填充Bean"

			"参数:beanName=demoApplication"
			"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"
			"参数:bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]"

			"9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例 	mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47];"

				......
	}

}

代码块20:populateBean

调用后置处理器

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

参数:bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47];
				......

					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) 调用后置处理器"

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

					"这句就是核心 	pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0; pvsToUse=PropertyValues: length=0;"

				......
	}

}

代码块21:postProcessProperties

注入

参数:pvs=PropertyValues: length=0

参数:beanName=demoApplication

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=demoApplication;
				......

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

			"(21) 注入"

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

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

				......
	}

}

代码块22:inject

注入

参数:beanName=demoApplication

参数: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=demoApplication;pvs=PropertyValues: length=0;
				......

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

				"(22) 注入"

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

				"这两个类继承InjectionMetadata.InjectedElement,各自重写了inject方法。 	pvs=PropertyValues: length=0; beanName=demoApplication;"

				......
	}

}

代码块23:inject

解析依赖关系

参数:beanName=demoApplication

参数: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=demoApplication;pvs=PropertyValues: length=0;
				......

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

					"(23) 解析依赖关系"

					"4.解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中"

				......
		}

}

小结:调用栈

demoApplication的属性userInfo依赖注入

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. *AbstractAutowireCapableBeanFactory.doCreateBean()
  11. *AbstractAutowireCapableBeanFactory.populateBean()
  12. *AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. *InjectionMetadata.inject()
  14. *AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()

根据类型获取所有UserInfo类型的bean定义,zhangsan和lisi

将断点打到DefaultListableBeanFactory.doGetBeanNamesForType方法,则代码执行过程如下

代码块24:resolveDependency

解析依赖关系

参数:descriptor=field ‘userInfo’

参数:requestingBeanName=demoApplication

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 'userInfo';requestingBeanName=demoApplication;
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
				......

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

				"(24) 解析依赖关系"

				"参数:descriptor=field 'userInfo'"
				"参数:beanName=demoApplication"

				"4.2 解析依赖关系,返回的result为创建好的依赖对象的bean实例"

				......
	}

}

代码块25:doResolveDependency

查找自动装配候选组件

参数:descriptor=field ‘userInfo’

参数:beanName=demoApplication

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, //descriptor=field 'userInfo';beanName=demoApplication;
			@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=zhangsan=class com.helloworld.entity.UserInfo;; 

			"(25) 查找自动装配候选组件"

			"参数:beanName=demoApplication"
			"参数:requiredType=class com.helloworld.entity.UserInfo"
			"参数:descriptor=field 'userInfo'"

			"6.查找与所需类型匹配的Bean实例(matchingBeans,key:beanName;value:匹配的bean实例,或者匹配的bean实例的类型) 	matchingBeans=zhangsan=class com.helloworld.entity.UserInfo;;"

				......
	}

}

代码块26:findAutowireCandidates

根据类型获取bean名称

参数:beanName=demoApplication

参数:requiredType=class com.helloworld.entity.UserInfo

参数:descriptor=field ‘userInfo’

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected Map<String, Object> findAutowireCandidates( //beanName=demoApplication;requiredType=class com.helloworld.entity.UserInfo;descriptor=field 'userInfo';
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
				......

		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( // 	candidateNames=zhangsan,lisi,; 

		this, requiredType, true, descriptor.isEager());

		"(26) 根据类型获取bean名称"

		"参数: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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"
		"参数:type=class com.helloworld.entity.UserInfo"
		"参数:includeNonSingletons=true"
		"参数:allowEagerInit=true"

		"candidateNames=zhangsan,lisi,;"

				......
	}

}

代码块27:beanNamesForTypeIncludingAncestors

根据类型获取bean名称

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

参数:type=class com.helloworld.entity.UserInfo

参数: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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;type=class com.helloworld.entity.UserInfo;includeNonSingletons=true;allowEagerInit=true;
			ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
				......

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

		"(27) 根据类型获取bean名称"

		"参数:type=class com.helloworld.entity.UserInfo"
		"参数:includeNonSingletons=true"
		"参数:allowEagerInit=true"

		"通过ListableBeanFactory的getBeanNamesForType方法来获取类型匹配的beanName列表 	result=zhangsan,lisi,;"

				......
	}

}

代码块28:getBeanNamesForType

根据类型获取bean名称

参数:type=class com.helloworld.entity.UserInfo

参数: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=class com.helloworld.entity.UserInfo;includeNonSingletons=true;allowEagerInit=true;
				......

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

		"(28) 根据类型获取bean名称"

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

		"如果缓存中没有获取到,那么只能重新获取,获取到之后就存入缓存 	resolvedBeanNames=zhangsan,lisi,;"

				......
	}

}

代码块29:doGetBeanNamesForType

根据类型判断是否匹配

参数: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;
				......

								isTypeMatch(beanName, type);

								"(29) 根据类型判断是否匹配"

				......
	}

}

小结:调用栈

根据类型获取所有UserInfo类型的bean定义,zhangsan和lisi

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  15. *DefaultListableBeanFactory.resolveDependency()
  16. *DefaultListableBeanFactory.doResolveDependency()
  17. *DefaultListableBeanFactory.findAutowireCandidates()
  18. *BeanFactoryUtils.beanNamesForTypeIncludingAncestors()
  19. *DefaultListableBeanFactory.getBeanNamesForType()
  20. *DefaultListableBeanFactory.doGetBeanNamesForType()

判断zhangsan与@Qualifier(“zhangsan”)的值"zhangsan"是否匹配

将断点打到BeanDefinitionHolder.matchesName方法,则代码执行过程如下

代码块30:findAutowireCandidates

是AUTOWIRE候选人

参数:beanName=demoApplication

参数:requiredType=class com.helloworld.entity.UserInfo

参数:descriptor=field ‘userInfo’

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected Map<String, Object> findAutowireCandidates( //beanName=demoApplication;requiredType=class com.helloworld.entity.UserInfo;descriptor=field 'userInfo';
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
				......
		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
				this, requiredType, true, descriptor.isEager());
		"(26)"


					if (isSelfReference(beanName, candidate) &&
							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) {

					"(30) 是AUTOWIRE候选人"

					"参数:beanName=zhangsan"

				......
	}

}

代码块31:isAutowireCandidate

是AUTOWIRE候选人

参数:beanName=zhangsan

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) //beanName=zhangsan;
			throws NoSuchBeanDefinitionException {
				......

		return isAutowireCandidate(beanName, descriptor, getAutowireCandidateResolver()); //解析beanName对应的bean是否有资格作为候选者 	true; 

		"(31) 是AUTOWIRE候选人"

		"参数:beanName=zhangsan"

		"解析beanName对应的bean是否有资格作为候选者 	true;"

	}

}

代码块32:isAutowireCandidate

是AUTOWIRE候选人

参数:beanName=zhangsan

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) //beanName=zhangsan;
			throws NoSuchBeanDefinitionException {
				......

			return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver); //将MergedBeanDefinition作为参数,解析beanName是否有资格作为候选者 	true; 

			"(32) 是AUTOWIRE候选人"

			"参数:beanName=zhangsan"

			"将MergedBeanDefinition作为参数,解析beanName是否有资格作为候选者 	true;"

				......
	}

}

代码块33:isAutowireCandidate

是AUTOWIRE候选人

参数:beanName=zhangsan

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd, //beanName=zhangsan;
			DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {
				......

		return resolver.isAutowireCandidate(

		"(33) 是AUTOWIRE候选人"

		"参数:bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication"

				......
	}

}

代码块34:isAutowireCandidate

检查限定符

参数:bdHolder=Bean definition with name ‘zhangsan’ and aliases []: Root bean: class [null]; scope=singleton; abstract=false; …

package org.springframework.beans.factory.annotation;

public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwareAutowireCandidateResolver{

	@Override
	public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { //bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication;
				......

			match = checkQualifiers(bdHolder, descriptor.getAnnotations()); //2.@Qualifiers注解检查 	match=true; 

			"(34) 检查限定符"

			"参数:bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication"
			"参数:annotationsToSearch=@org.springframework.beans.factory.annotation.Autowired(required=true),@org.springframework.beans.factory.annotation.Qualifier(value=zhangsan),"

			"2.@Qualifiers注解检查 	match=true;"

				......
	}

}

代码块35:checkQualifiers

检查限定符

参数:bdHolder=Bean definition with name ‘zhangsan’ and aliases []: Root bean: class [null]; scope=singleton; abstract=false; …

参数:annotationsToSearch=@org.springframework.beans.factory.annotation.Autowired(required=true),@org.springframework.beans.fa…

package org.springframework.beans.factory.annotation;

public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwareAutowireCandidateResolver{

	protected boolean checkQualifiers(BeanDefinitionHolder bdHolder, Annotation[] annotationsToSearch) { //bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication;annotationsToSearch=@org.springframework.beans.factory.annotation.Autowired(required=true),@org.springframework.beans.factory.annotation.Qualifier(value=zhangsan),;
				......

				if (!checkQualifier(bdHolder, annotation, typeConverter)) {

				"(35) 检查限定符"

				"参数:bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication"

				......
	}

}

代码块36:checkQualifier

匹配名称

参数:bdHolder=Bean definition with name ‘zhangsan’ and aliases []: Root bean: class [null]; scope=singleton; abstract=false; …

package org.springframework.beans.factory.annotation;

public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwareAutowireCandidateResolver{

	protected boolean checkQualifier( //bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication;
			BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {
				......

			if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
					expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {

			"(36) 匹配名称"

			"参数:candidateName=zhangsan"

				......
	}

}

代码块37:matchesName

匹配名称

参数:candidateName=zhangsan

package org.springframework.beans.factory.config;

public class BeanDefinitionHolder implements BeanMetadataElement{

	public boolean matchesName(@Nullable String candidateName) { //candidateName=zhangsan;

		return (candidateName != null && (candidateName.equals(this.beanName) ||

		"(37) 匹配名称"

				......
	}

}

小结:调用栈

判断zhangsan与@Qualifier(“zhangsan”)的值"zhangsan"是否匹配

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  15. DefaultListableBeanFactory.resolveDependency()
  16. DefaultListableBeanFactory.doResolveDependency()
  17. *DefaultListableBeanFactory.findAutowireCandidates()
  18. *DefaultListableBeanFactory.isAutowireCandidate()
  19. *DefaultListableBeanFactory.isAutowireCandidate()
  20. *DefaultListableBeanFactory.isAutowireCandidate()
  21. *QualifierAnnotationAutowireCandidateResolver.isAutowireCandidate()
  22. *QualifierAnnotationAutowireCandidateResolver.checkQualifiers()
  23. *QualifierAnnotationAutowireCandidateResolver.checkQualifier()
  24. *BeanDefinitionHolder.matchesName()

匹配到zhangsan,将zhangsan添加到候选组件

将断点打到DefaultListableBeanFactory.addCandidateEntry方法,则代码执行过程如下

代码块38:findAutowireCandidates

添加候选人条目

参数:beanName=demoApplication

参数:requiredType=class com.helloworld.entity.UserInfo

参数:descriptor=field ‘userInfo’

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected Map<String, Object> findAutowireCandidates( //beanName=demoApplication;requiredType=class com.helloworld.entity.UserInfo;descriptor=field 'userInfo';
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
				......
		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
				this, requiredType, true, descriptor.isEager());
		"(26)"

					if (isSelfReference(beanName, candidate) &&
							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) {
					"(30)"


						addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中 	descriptor=field 'userInfo'; requiredType=class com.helloworld.entity.UserInfo; candidate=zhangsan; result=zhangsan=class com.helloworld.entity.UserInfo;; 

						"(38) 添加候选人条目"

						"参数:candidateName=zhangsan"
						"参数:descriptor=field 'userInfo'"
						"参数:requiredType=class com.helloworld.entity.UserInfo"

						"&& candidate允许依赖注入,则将候选者添加到result中 	descriptor=field 'userInfo'; requiredType=class com.helloworld.entity.UserInfo; candidate=zhangsan; result=zhangsan=class com.helloworld.entity.UserInfo;;"

				......
	}

}

代码块39:addCandidateEntry

添加候选组件

参数:candidateName=zhangsan

参数:descriptor=field ‘userInfo’

参数:requiredType=class com.helloworld.entity.UserInfo

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	private void addCandidateEntry(Map<String, Object> candidates, String candidateName, //candidateName=zhangsan;descriptor=field 'userInfo';requiredType=class com.helloworld.entity.UserInfo;
			DependencyDescriptor descriptor, Class<?> requiredType) {
				......

			candidates.put(candidateName, getType(candidateName)); //3.将beanName -> bean实例的类型 的映射添加到candidates(此时的value为bean实例的类型) 	candidateName=zhangsan; 

			"(39) 添加候选组件"

			"3.将beanName -> bean实例的类型 的映射添加到candidates(此时的value为bean实例的类型) 	candidateName=zhangsan;"

				......
	}

}

小结:调用栈

匹配到zhangsan,将zhangsan添加到候选组件

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  15. DefaultListableBeanFactory.resolveDependency()
  16. DefaultListableBeanFactory.doResolveDependency()
  17. *DefaultListableBeanFactory.findAutowireCandidates()
  18. *DefaultListableBeanFactory.addCandidateEntry()

实例化zhangsan

将断点打到DependencyDescriptor.resolveCandidate方法,则代码执行过程如下

代码块40:resolveCandidate

获取bean对象

参数:beanName=zhangsan

参数:requiredType=class com.helloworld.entity.UserInfo

参数: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=zhangsan;requiredType=class com.helloworld.entity.UserInfo;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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;
			throws BeansException {
				......

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

		"(40) 获取bean对象"

		"直接从容器中获取真正的对象"

	}

}

小结:调用栈

实例化zhangsan

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  15. DefaultListableBeanFactory.resolveDependency()
  16. DefaultListableBeanFactory.doResolveDependency()
  17. *DependencyDescriptor.resolveCandidate()

此时demoApplication和zhangsan实例化完毕,执行依赖注入

将断点打到AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject方法,则代码执行过程如下

代码块41:inject

使用反射执行依赖注入

参数:beanName=demoApplication

参数: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=demoApplication;pvs=PropertyValues: length=0;
				......
					value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
					"(23)"


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

				"(41) 使用反射执行依赖注入"

				"13.通过反射为属性赋值,将解析出来的bean实例赋值给field"

				......
		}

}

小结:调用栈

此时demoApplication和zhangsan实例化完毕,执行依赖注入

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. *AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()

完整代码版

定位到创建bean实例demoApplication

将断点打到AbstractAutowireCapableBeanFactory.createBeanInstance方法,则代码执行过程如下

代码块1:main

构造器

参数:args=[]

package com.helloworld;

public class DemoApplication {

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

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DemoApplication.class);

        "(1) 构造器"

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

        UserInfo userInfo = (UserInfo) ctx.getBean("zhangsan");
    }

}

代码块2:AnnotationConfigApplicationContext()

刷新

参数: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) 刷新"

	}

}

代码块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.
			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,userServiceImpl,zhangsan,lisi,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,userServiceImpl,zhangsan,lisi,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,userServiceImpl,zhangsan,lisi,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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"

				"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,userServiceImpl,zhangsan,lisi,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的元数据......
			}
		}
	}

}

代码块4:finishBeanFactoryInitialization

预实例化单例

参数: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,userServiceImpl,zhangsan,lisi,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,userServiceImpl,zhangsan,lisi,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,userServiceImpl,zhangsan,lisi,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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

		"(4) 预实例化单例"

		"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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;"

	}

}

代码块5:preInstantiateSingletons

获取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);
		}

		// 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,userServiceImpl,zhangsan,lisi,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=userServiceImpl; beanName=zhangsan; beanName=lisi; 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$$fa872306]; 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\qualifier\target\classes\com\helloworld\aop\TestAspect.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\qualifier\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$$fa872306]; 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\qualifier\target\classes\com\helloworld\aop\TestAspect.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\qualifier\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=userServiceImpl; beanName=zhangsan; beanName=lisi; beanName=org.springframework.aop.config.internalAutoProxyCreator; 

					"(5) 获取Bean"

					"参数:name=demoApplication"

					"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=userServiceImpl; beanName=zhangsan; beanName=lisi; 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=userServiceImpl; beanName=zhangsan; beanName=lisi; 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()?方法,可以在回调中做一些事情?
				}
			}
		}
	}

}

代码块6:getBean

获取bean

参数:name=demoApplication

package org.springframework.beans.factory.support;

public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{

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

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

		"(6) 获取bean"

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

		"获取name对应的bean实例,如果不存在,则创建一个"

	}

}

代码块7:doGetBean

获取单例

参数:name=demoApplication

参数: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=demoApplication;typeCheckOnly=false;
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

		final String beanName = transformedBeanName(name); //1.解析beanName,主要是解析别名、去掉FactoryBean的前缀“&” 	beanName=demoApplication; 
		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=demoApplication; 
			}

			try {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //7.根据beanName重新获取MergedBeanDefinition(步骤6将MergedBeanDefinition删除了,这边获取一个新的) 	mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
				checkMergedBeanDefinition(mbd, beanName, args); //7.1 检查MergedBeanDefinition 	mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 

				// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 

					sharedInstance = getSingleton(beanName, () -> {

					"(7) 获取单例"

					"参数:beanName=demoApplication"

						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实例对象
	}

}

代码块8:getSingleton

创建Bean

参数:beanName=demoApplication

package org.springframework.beans.factory.support;

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry{

	public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { //beanName=demoApplication;
		Assert.notNull(beanName, "Bean name must not be null"); //beanName的非空判断,为空抛出一个运行时异常 	beanName=demoApplication; 
		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=demoApplication; 
				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"

					"参数:beanName=demoApplication"
					"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"

					"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=demoApplication; 
				}
				if (newSingleton) {
					addSingleton(beanName, singletonObject); //8.如果是新的单例对象,将beanName和对应的bean实例添加到缓存中(singletonObjects、registeredSingletons) 	beanName=demoApplication; 
				}
			}
			return singletonObject; //返回缓存中的实例
		}
	}

}

代码块9:createBean

创建bean

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
			throws BeanCreationException {

		if (logger.isTraceEnabled()) { //1. 循环 PropertySources
			logger.trace("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd; //bean定义信息 	mbdToUse=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 

		// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; 
		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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
		}
		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的方法)

			"(9) 创建bean"

			"参数:beanName=demoApplication"
			"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"

			"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);
		}
	}

}

代码块10:doCreateBean

创建Bean实例

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null; //1.新建Bean包装类
		if (mbd.isSingleton()) { //9.针对不同的scope进行bean的创建 	mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
			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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 

			"(10) 创建Bean实例"

			"参数:beanName=demoApplication"
			"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"

			"3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper 	instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47];"

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

		// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 
				}
				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=demoApplication; 
		}

		// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 
			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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

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

}

代码块11:createBeanInstance

使用默认构造器,实例化bean

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

package org.springframework.beans.factory.support;

public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{

	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { //beanName=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
		// Make sure bean class is actually resolved at this point.
		Class<?> beanClass = resolveBeanClass(mbd, beanName); //解析bean的类型信息 	beanClass=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; 

		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}

		Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); //如果存在 Supplier 回调,则使用给定的回调方法初始化策略
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName); //如果有实例工厂,直接调用工厂方法
		}

		if (mbd.getFactoryMethodName() != null) { //1.如果存在工厂方法则使用工厂方法实例化bean对象
			return instantiateUsingFactoryMethod(beanName, mbd, args); //采用工厂方法实例化,不熟悉这个概念的读者请看附录,注意,不是 FactoryBean
		}

		// Shortcut when re-creating the same bean...
		boolean resolved = false; //resolved: 构造函数或工厂方法是否已经解析过 	resolved=false; 
		boolean autowireNecessary = false; //autowireNecessary: 是否需要自动注入(即是否需要解析构造函数参数) 	autowireNecessary=false; 
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) { //2.加锁
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true; //2.1 如果resolvedConstructorOrFactoryMethod缓存不为空,则将resolved标记为已解析
					autowireNecessary = mbd.constructorArgumentsResolved; //2.2 根据constructorArgumentsResolved判断是否需要自动注入
				}
			}
		}
		if (resolved) {
			if (autowireNecessary) { //3.如果已经解析过,则使用resolvedConstructorOrFactoryMethod缓存里解析好的构造函数方法
				return autowireConstructor(beanName, mbd, null, null); //3.1 需要自动注入,则执行构造函数自动注入
			}
			else {
				return instantiateBean(beanName, mbd); //6.没有特殊处理,则使用默认的构造函数进行bean的实例化
			}
		}

		// Candidate constructors for autowiring?
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); //4.应用后置处理器SmartInstantiationAwareBeanPostProcessor,拿到bean的候选构造函数
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args); //5.如果ctors不为空 || mbd的注入方式为AUTOWIRE_CONSTRUCTOR || mdb定义了构造函数的参数值 || args不为空,则执行构造函数自动注入
		}

		// Preferred constructors for default construction?
		ctors = mbd.getPreferredConstructors(); //获得首选的构造器,可能是默认构造器
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null); //构造函数自动注入
		}

		// No special handling: simply use no-arg constructor.

		return instantiateBean(beanName, mbd); //6.没有特殊处理,则使用默认的构造函数进行bean的实例化 	org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 

		"(11) 使用默认构造器,实例化bean"

		"6.没有特殊处理,则使用默认的构造函数进行bean的实例化 	org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47];"

	}

}

小结:调用栈

定位到创建bean实例demoApplication

  1. *DemoApplication.main()
  2. *AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. *AbstractApplicationContext.refresh()
  4. *AbstractApplicationContext.finishBeanFactoryInitialization()
  5. *DefaultListableBeanFactory.preInstantiateSingletons()
  6. *AbstractBeanFactory.getBean()
  7. *AbstractBeanFactory.doGetBean()
  8. *DefaultSingletonBeanRegistry.getSingleton()
  9. *AbstractAutowireCapableBeanFactory.createBean()
  10. *AbstractAutowireCapableBeanFactory.doCreateBean()
  11. *AbstractAutowireCapableBeanFactory.createBeanInstance()

找到demoApplication的成员变量userInfo的自动装配注解及属性

将断点打到AutowiredAnnotationBeanPostProcessor.findAutowiredAnnotation方法,则代码执行过程如下

代码块12:doCreateBean

应用合并的Bean定义后处理器

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
			throws BeanCreationException {

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

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

		// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 

					"(12) 应用合并的Bean定义后处理器"

					"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"
					"参数:beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306"
					"参数:beanName=demoApplication"

					"Autowired注解正是通过此方法实现注入类型的预解析 	beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication;"

				}
				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=demoApplication; 
		}

		// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 
			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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

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

}

代码块13:applyMergedBeanDefinitionPostProcessors

后期处理合并Bean定义

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

参数:beanType=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

参数:beanName=demoApplication

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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;beanName=demoApplication;
		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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 

				"(13) 后期处理合并Bean定义"

				"参数:beanDefinition=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"
				"参数:beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306"
				"参数:beanName=demoApplication"

				"执行postProcessMergedBeanDefinition 	beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication;"

			}
		}
	}

}

代码块14:postProcessMergedBeanDefinition

查找@Autowired自动装配元数据

参数:beanDefinition=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abst…

参数:beanType=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

参数:beanName=demoApplication

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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;beanType=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;beanName=demoApplication;

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

		"(14) 查找@Autowired自动装配元数据"

		"参数:beanName=demoApplication"
		"参数:clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306"

		"1.在指定Bean中查找使用@Autowire注解的元数据 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@192d43ce;"

		metadata.checkConfigMembers(beanDefinition); //2.检查元数据中的注解信息 	beanDefinition=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
	}

}

代码块15:findAutowiringMetadata

构建自动配置元数据

参数:beanName=demoApplication

参数:clazz=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { //beanName=demoApplication;clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;
		// 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=demoApplication; 
		// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; 
			synchronized (this.injectionMetadataCache) {
				metadata = this.injectionMetadataCache.get(cacheKey); //4.加锁后,再次从缓存中获取beanName对应的InjectionMetadata
				if (InjectionMetadata.needsRefresh(metadata, clazz)) { //5.加锁后,再次检查InjectionMetadata是否需要刷新 	clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; 
					if (metadata != null) { //pvs是null前面写的传null
						metadata.clear(pvs); //6.如果需要刷新,并且metadata不为空,则先移除
					}

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

					"(15) 构建自动配置元数据"

					"参数:clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306"

					"这里的元素包括AutowiredFieldElement和AutowiredMethodElement) 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@192d43ce;"

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

}

代码块16:buildAutowiringMetadata

查找@Autowired注解

参数:clazz=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

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

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


			ReflectionUtils.doWithLocalFields(targetClass, field -> { // 	targetClass=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; targetClass=class com.helloworld.DemoApplication; 

			AnnotationAttributes ann = findAutowiredAnnotation(field); //2.2.1 获取field上的@Autowired注解信息

			"(16) 查找@Autowired注解"

			"参数:ao=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo"

			"targetClass=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; targetClass=class com.helloworld.DemoApplication;"

				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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; targetClass=class com.helloworld.DemoApplication; 
				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.entity.UserInfo com.helloworld.DemoApplication.userInfo,; 
			targetClass = targetClass.getSuperclass(); //2.5 在解析完targetClass之后,递归解析父类,将所有的@Autowired的属性和方法收集起来,且类的层级越高其属性会被越优先注入 	targetClass=class com.helloworld.DemoApplication; 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@192d43ce; 
	}

}

代码块17:findAutowiredAnnotation

找到userInfo的@Autowired注解及注解属性,构建元数据

参数:ao=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	@Nullable
	private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) { //ao=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo;
		if (ao.getAnnotations().length > 0) {  // autowiring annotations have to be local // 	ao=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo; 
			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;; 

				"(17) 找到userInfo的@Autowired注解及注解属性,构建元数据"

				"3.拿到注解的合并注解属性,@Autowire在这边拿到,required=true(默认属性) 	attributes=required=true;;"

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

}

小结:调用栈

找到demoApplication的成员变量userInfo的自动装配注解及属性

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. *AbstractAutowireCapableBeanFactory.doCreateBean()
  11. *AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()
  12. *AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition()
  13. *AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata()
  14. *AutowiredAnnotationBeanPostProcessor.buildAutowiringMetadata()
  15. *AutowiredAnnotationBeanPostProcessor.findAutowiredAnnotation()

将找到的@Autowired注解元数据放入缓存

将断点打到AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata方法,则代码执行过程如下

代码块18:findAutowiringMetadata

将找到的@Autowired注解元数据放入缓存

参数:beanName=demoApplication

参数:clazz=class com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306

package org.springframework.beans.factory.annotation;

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{

	private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { //beanName=demoApplication;clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306;
		// 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=demoApplication; 
		// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; 
			synchronized (this.injectionMetadataCache) {
				metadata = this.injectionMetadataCache.get(cacheKey); //4.加锁后,再次从缓存中获取beanName对应的InjectionMetadata
				if (InjectionMetadata.needsRefresh(metadata, clazz)) { //5.加锁后,再次检查InjectionMetadata是否需要刷新 	clazz=class com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306; 
					if (metadata != null) { //pvs是null前面写的传null
						metadata.clear(pvs); //6.如果需要刷新,并且metadata不为空,则先移除
					}
					metadata = buildAutowiringMetadata(clazz);
					"(15)"


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

					"(18) 将找到的@Autowired注解元数据放入缓存"

					"8.将解析的元数据放到injectionMetadataCache缓存,以备复用,每一个类只解析一次 	cacheKey=demoApplication; metadata=org.springframework.beans.factory.annotation.InjectionMetadata@192d43ce;"

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

}

小结:调用栈

将找到的@Autowired注解元数据放入缓存

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()
  12. AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition()
  13. *AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata()

demoApplication的属性userInfo依赖注入

将断点打到AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject方法,则代码执行过程如下

代码块19:doCreateBean

填充Bean

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
			throws BeanCreationException {

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

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

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
					"(12)"

				}
				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=demoApplication; 
		}

		// 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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 

			"(19) 填充Bean"

			"参数:beanName=demoApplication"
			"参数:mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null"
			"参数:bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]"

			"9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例 	mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; instanceWrapper=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47];"

			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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; beanName=demoApplication; 
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

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

}

代码块20:populateBean

调用后置处理器

参数:beanName=demoApplication

参数:mbd=Root bean: class [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa872306]; scope=singleton; abstract=false;…

参数:bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplicationEnhancerBySpringCGLIBfa…

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=demoApplication;mbd=Root bean: class [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47];
		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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; 
			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; 

					"(20) 调用后置处理器"

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

					"这句就是核心 	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.DemoApplication$$EnhancerBySpringCGLIB$$fa872306]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; pvs=PropertyValues: length=0; beanName=demoApplication; bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.DemoApplication$$EnhancerBySpringCGLIB$$fa872306@5119fb47]; 
		}
	}

}

代码块21:postProcessProperties

注入

参数:pvs=PropertyValues: length=0

参数:beanName=demoApplication

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=demoApplication;
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); //1.在指定Bean中查找使用@Autowire注解的元数据 	metadata=org.springframework.beans.factory.annotation.InjectionMetadata@192d43ce; 
		try {

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

			"(21) 注入"

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

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

		}
		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=demoApplication

参数: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=demoApplication;pvs=PropertyValues: length=0;
		Collection<InjectedElement> checkedElements = this.checkedElements; //获取对象中加了@Autowired注解的元数据集合 	checkedElements=AutowiredFieldElement for private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo,; 
		Collection<InjectedElement> elementsToIterate = // 	elementsToIterate=AutowiredFieldElement for private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo,; 
				(checkedElements != null ? checkedElements : this.injectedElements);
		if (!elementsToIterate.isEmpty()) { // 	elementsToIterate=AutowiredFieldElement for private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo,; 
			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=demoApplication; 

				"(22) 注入"

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

				"这两个类继承InjectionMetadata.InjectedElement,各自重写了inject方法。 	pvs=PropertyValues: length=0; beanName=demoApplication;"

			}
		}
	}

}

代码块23:inject

解析依赖关系

参数:beanName=demoApplication

参数: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=demoApplication;pvs=PropertyValues: length=0;
			Field field = (Field) this.member; //1.拿到该元数据的属性值 	field=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo; 
			Object value;
			if (this.cached) { //2.如果缓存中已经存在,则直接从缓存中解析属性
				value = resolvedCachedArgument(beanName, this.cachedFieldValue); //第一次注入的时候肯定没有缓存这里也是对原型情况的处理
			}
			else {
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required); //3.将field封装成DependencyDescriptor 	desc=field 'userInfo'; 
				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) 解析依赖关系"

					"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 'userInfo'; 
							registerDependentBeans(beanName, autowiredBeanNames); //7.注册依赖关系到缓存(beanName 依赖 autowiredBeanNames) 	autowiredBeanNames=zhangsan,; beanName=demoApplication; 
							if (autowiredBeanNames.size() == 1) { //8.如果属性依赖注入的bean只有一个(正常都是一个) 	autowiredBeanNames=zhangsan,; 
								String autowiredBeanName = autowiredBeanNames.iterator().next(); //自动注入的名称 	autowiredBeanName=zhangsan; 
								if (beanFactory.containsBean(autowiredBeanName) &&
										beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { // 	autowiredBeanName=zhangsan; 
									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.entity.UserInfo com.helloworld.DemoApplication.userInfo; 
				field.set(bean, value); //13.通过反射为属性赋值,将解析出来的bean实例赋值给field
			}
		}

}

小结:调用栈

demoApplication的属性userInfo依赖注入

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. *AbstractAutowireCapableBeanFactory.doCreateBean()
  11. *AbstractAutowireCapableBeanFactory.populateBean()
  12. *AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. *InjectionMetadata.inject()
  14. *AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()

根据类型获取所有UserInfo类型的bean定义,zhangsan和lisi

将断点打到DefaultListableBeanFactory.doGetBeanNamesForType方法,则代码执行过程如下

代码块24:resolveDependency

解析依赖关系

参数:descriptor=field ‘userInfo’

参数:requestingBeanName=demoApplication

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 'userInfo';requestingBeanName=demoApplication;
			@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实例

				"(24) 解析依赖关系"

				"参数:descriptor=field 'userInfo'"
				"参数:beanName=demoApplication"

				"4.2 解析依赖关系,返回的result为创建好的依赖对象的bean实例"

			}
			return result;
		}
	}

}

代码块25:doResolveDependency

查找自动装配候选组件

参数:descriptor=field ‘userInfo’

参数:beanName=demoApplication

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, //descriptor=field 'userInfo';beanName=demoApplication;
			@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=class com.helloworld.entity.UserInfo; 
			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=zhangsan=class com.helloworld.entity.UserInfo;; 

			"(25) 查找自动装配候选组件"

			"参数:beanName=demoApplication"
			"参数:requiredType=class com.helloworld.entity.UserInfo"
			"参数:descriptor=field 'userInfo'"

			"6.查找与所需类型匹配的Bean实例(matchingBeans,key:beanName;value:匹配的bean实例,或者匹配的bean实例的类型) 	matchingBeans=zhangsan=class com.helloworld.entity.UserInfo;;"

			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=zhangsan; 
				instanceCandidate = entry.getValue(); //instanceCandidate可以是已经实例化的对象,也可以是对应类型的class对象 	instanceCandidate=class com.helloworld.entity.UserInfo; 
			}

			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(autowiredBeanName); //9.将依赖的beanName加到autowiredBeanNames中 	autowiredBeanName=zhangsan; 
			}
			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.执行结束,将注入点修改成原来的注入点
		}
	}

}

代码块26:findAutowireCandidates

根据类型获取bean名称

参数:beanName=demoApplication

参数:requiredType=class com.helloworld.entity.UserInfo

参数:descriptor=field ‘userInfo’

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected Map<String, Object> findAutowireCandidates( //beanName=demoApplication;requiredType=class com.helloworld.entity.UserInfo;descriptor=field 'userInfo';
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {


		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( // 	candidateNames=zhangsan,lisi,; 

		this, requiredType, true, descriptor.isEager());

		"(26) 根据类型获取bean名称"

		"参数: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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"
		"参数:type=class com.helloworld.entity.UserInfo"
		"参数:includeNonSingletons=true"
		"参数:allowEagerInit=true"

		"candidateNames=zhangsan,lisi,;"

				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=zhangsan; candidate=lisi; 
			if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { //3.1 如果不是自引用 && candidate有资格作为依赖注入的候选者
				addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中
			}
		}
		if (result.isEmpty()) { //如果结果为空,则返回需要更多的输入
			boolean multiple = indicatesMultipleBeans(requiredType); //如果依旧没找到,执行降级匹配 	multiple=false; 
			// Consider fallback matches if the first pass failed to find anything...
			DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); //4.1 使用降级匹配(跟正常匹配类似)
			for (String candidate : candidateNames) { //5.如果使用降级匹配结果还是空,则考虑自引用 	candidate=zhangsan; candidate=lisi; 
				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.如果使用降级匹配结果还是空,则考虑自引用 	candidate=zhangsan; candidate=lisi; 
					if (isSelfReference(beanName, candidate) &&
							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) { // 	beanName=demoApplication; candidate=zhangsan; 
						addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中 	descriptor=field 'userInfo'; requiredType=class com.helloworld.entity.UserInfo; candidate=zhangsan; result=zhangsan=class com.helloworld.entity.UserInfo;; 
					}
				}
			}
		}
		return result; // 	zhangsan=class com.helloworld.entity.UserInfo;; 
	}

}

代码块27:beanNamesForTypeIncludingAncestors

根据类型获取bean名称

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

参数:type=class com.helloworld.entity.UserInfo

参数: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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;type=class com.helloworld.entity.UserInfo;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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy; 

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

		"(27) 根据类型获取bean名称"

		"参数:type=class com.helloworld.entity.UserInfo"
		"参数:includeNonSingletons=true"
		"参数:allowEagerInit=true"

		"通过ListableBeanFactory的getBeanNamesForType方法来获取类型匹配的beanName列表 	result=zhangsan,lisi,;"

		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,userServiceImpl,zhangsan,lisi,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; // 	zhangsan,lisi,; 
	}

}

代码块28:getBeanNamesForType

根据类型获取bean名称

参数:type=class com.helloworld.entity.UserInfo

参数: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=class com.helloworld.entity.UserInfo;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=zhangsan,lisi,; 

		"(28) 根据类型获取bean名称"

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

		"如果缓存中没有获取到,那么只能重新获取,获取到之后就存入缓存 	resolvedBeanNames=zhangsan,lisi,;"

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

}

代码块29:doGetBeanNamesForType

根据类型判断是否匹配

参数: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.
		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=userServiceImpl; beanName=zhangsan; beanName=lisi; 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=userServiceImpl; beanName=zhangsan; beanName=lisi; 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$$fa872306]; 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\qualifier\target\classes\com\helloworld\aop\TestAspect.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\qualifier\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$$fa872306]; 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\qualifier\target\classes\com\helloworld\aop\TestAspect.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\qualifier\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; 
						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=true; matchFound=true; matchFound=false; 
								(allowEagerInit || !isFactoryBean ||
										(dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) &&
								(includeNonSingletons ||
										(dbd != null ? mbd.isSingleton() : isSingleton(beanName))) &&

								isTypeMatch(beanName, type);

								"(29) 根据类型判断是否匹配"

						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=zhangsan; beanName=lisi; 
						}
					}
				}
				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 	zhangsan,lisi,; 
	}

}

小结:调用栈

根据类型获取所有UserInfo类型的bean定义,zhangsan和lisi

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  15. *DefaultListableBeanFactory.resolveDependency()
  16. *DefaultListableBeanFactory.doResolveDependency()
  17. *DefaultListableBeanFactory.findAutowireCandidates()
  18. *BeanFactoryUtils.beanNamesForTypeIncludingAncestors()
  19. *DefaultListableBeanFactory.getBeanNamesForType()
  20. *DefaultListableBeanFactory.doGetBeanNamesForType()

判断zhangsan与@Qualifier(“zhangsan”)的值"zhangsan"是否匹配

将断点打到BeanDefinitionHolder.matchesName方法,则代码执行过程如下

代码块30:findAutowireCandidates

是AUTOWIRE候选人

参数:beanName=demoApplication

参数:requiredType=class com.helloworld.entity.UserInfo

参数:descriptor=field ‘userInfo’

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected Map<String, Object> findAutowireCandidates( //beanName=demoApplication;requiredType=class com.helloworld.entity.UserInfo;descriptor=field 'userInfo';
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {

		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
				this, requiredType, true, descriptor.isEager());
		"(26)"

				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=zhangsan; candidate=lisi; 
			if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { //3.1 如果不是自引用 && candidate有资格作为依赖注入的候选者
				addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中
			}
		}
		if (result.isEmpty()) { //如果结果为空,则返回需要更多的输入
			boolean multiple = indicatesMultipleBeans(requiredType); //如果依旧没找到,执行降级匹配 	multiple=false; 
			// Consider fallback matches if the first pass failed to find anything...
			DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); //4.1 使用降级匹配(跟正常匹配类似)
			for (String candidate : candidateNames) { //5.如果使用降级匹配结果还是空,则考虑自引用 	candidate=zhangsan; candidate=lisi; 
				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.如果使用降级匹配结果还是空,则考虑自引用 	candidate=zhangsan; candidate=lisi; 

					if (isSelfReference(beanName, candidate) &&
							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) {

					"(30) 是AUTOWIRE候选人"

					"参数:beanName=zhangsan"

							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) { // 	beanName=demoApplication; candidate=zhangsan; 
						addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中 	descriptor=field 'userInfo'; requiredType=class com.helloworld.entity.UserInfo; candidate=zhangsan; result=zhangsan=class com.helloworld.entity.UserInfo;; 
					}
				}
			}
		}
		return result; // 	zhangsan=class com.helloworld.entity.UserInfo;; 
	}

}

代码块31:isAutowireCandidate

是AUTOWIRE候选人

参数:beanName=zhangsan

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	@Override
	public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) //beanName=zhangsan;
			throws NoSuchBeanDefinitionException {


		return isAutowireCandidate(beanName, descriptor, getAutowireCandidateResolver()); //解析beanName对应的bean是否有资格作为候选者 	true; 

		"(31) 是AUTOWIRE候选人"

		"参数:beanName=zhangsan"

		"解析beanName对应的bean是否有资格作为候选者 	true;"

	}

}

代码块32:isAutowireCandidate

是AUTOWIRE候选人

参数:beanName=zhangsan

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) //beanName=zhangsan;
			throws NoSuchBeanDefinitionException {

		String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); //1.解析beanName,去掉FactoryBean的修饰符“&” 	beanDefinitionName=zhangsan; 
		if (containsBeanDefinition(beanDefinitionName)) { // 	beanDefinitionName=zhangsan; 

			return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver); //将MergedBeanDefinition作为参数,解析beanName是否有资格作为候选者 	true; 

			"(32) 是AUTOWIRE候选人"

			"参数:beanName=zhangsan"

			"将MergedBeanDefinition作为参数,解析beanName是否有资格作为候选者 	true;"

		}
		else if (containsSingleton(beanName)) {
			return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver); //3.singletonObjects缓存中存在beanName:使用beanName构建RootBeanDefinition作为参数,解析beanName是否有资格作为候选者
		}

		BeanFactory parent = getParentBeanFactory(); //4.在beanDefinitionMap缓存和singletonObjects缓存中都不存在,则在parentBeanFactory中递归解析beanName是否有资格作为候选者
		if (parent instanceof DefaultListableBeanFactory) {
			// No bean definition found in this factory -> delegate to parent.
			return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver);
		}
		else if (parent instanceof ConfigurableListableBeanFactory) {
			// If no DefaultListableBeanFactory, can't pass the resolver along.
			return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor);
		}
		else {
			return true;
		}
	}

}

代码块33:isAutowireCandidate

是AUTOWIRE候选人

参数:beanName=zhangsan

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd, //beanName=zhangsan;
			DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {

		String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); //1.解析beanName,去掉FactoryBean的修饰符“&” 	beanDefinitionName=zhangsan; 
		resolveBeanClass(mbd, beanDefinitionName); //2.解析mbd的beanClass 	beanDefinitionName=zhangsan; 
		if (mbd.isFactoryMethodUnique && mbd.factoryMethodToIntrospect == null) {
			new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd); //3.如果缓存中已经存在解析的构造函数或工厂方法,则解析mbd中的工厂方法,并替换掉缓存中的方法
		}

		return resolver.isAutowireCandidate(

		"(33) 是AUTOWIRE候选人"

		"参数:bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication"

				new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor); // 	true; 
	}

}

代码块34:isAutowireCandidate

检查限定符

参数:bdHolder=Bean definition with name ‘zhangsan’ and aliases []: Root bean: class [null]; scope=singleton; abstract=false; …

package org.springframework.beans.factory.annotation;

public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwareAutowireCandidateResolver{

	@Override
	public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { //bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication;
		boolean match = super.isAutowireCandidate(bdHolder, descriptor); //1.调用父类方法判断此bean是否可以自动注入到其他bean 	match=true; 
		if (match) {

			match = checkQualifiers(bdHolder, descriptor.getAnnotations()); //2.@Qualifiers注解检查 	match=true; 

			"(34) 检查限定符"

			"参数:bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication"
			"参数:annotationsToSearch=@org.springframework.beans.factory.annotation.Autowired(required=true),@org.springframework.beans.factory.annotation.Qualifier(value=zhangsan),"

			"2.@Qualifiers注解检查 	match=true;"

			if (match) {
				MethodParameter methodParam = descriptor.getMethodParameter(); //相当于@Value注解标注在方法入参上 也是阔仪的~~~~~
				if (methodParam != null) {
					Method method = methodParam.getMethod();
					if (method == null || void.class == method.getReturnType()) {
						match = checkQualifiers(bdHolder, methodParam.getMethodAnnotations()); //2. 查找方法上的注解
					}
				}
			}
		}
		return match; // 	true; 
	}

}

代码块35:checkQualifiers

检查限定符

参数:bdHolder=Bean definition with name ‘zhangsan’ and aliases []: Root bean: class [null]; scope=singleton; abstract=false; …

参数:annotationsToSearch=@org.springframework.beans.factory.annotation.Autowired(required=true),@org.springframework.beans.fa…

package org.springframework.beans.factory.annotation;

public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwareAutowireCandidateResolver{

	protected boolean checkQualifiers(BeanDefinitionHolder bdHolder, Annotation[] annotationsToSearch) { //bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication;annotationsToSearch=@org.springframework.beans.factory.annotation.Autowired(required=true),@org.springframework.beans.factory.annotation.Qualifier(value=zhangsan),;
		if (ObjectUtils.isEmpty(annotationsToSearch)) {
			return true;
		}
		SimpleTypeConverter typeConverter = new SimpleTypeConverter();
		for (Annotation annotation : annotationsToSearch) {
			Class<? extends Annotation> type = annotation.annotationType(); //注释类型 	type=interface org.springframework.beans.factory.annotation.Autowired; type=interface org.springframework.beans.factory.annotation.Qualifier; 
			boolean checkMeta = true; // 	checkMeta=true; checkMeta=true; 
			boolean fallbackToMeta = false; // 	fallbackToMeta=false; fallbackToMeta=false; 
			if (isQualifier(type)) { // 	type=interface org.springframework.beans.factory.annotation.Qualifier; 

				if (!checkQualifier(bdHolder, annotation, typeConverter)) {

				"(35) 检查限定符"

				"参数:bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication"

					fallbackToMeta = true;
				}
				else {
					checkMeta = false; // 	checkMeta=false; 
				}
			}
			if (checkMeta) {
				boolean foundMeta = false; // 	foundMeta=false; 
				for (Annotation metaAnn : type.getAnnotations()) {
					Class<? extends Annotation> metaType = metaAnn.annotationType(); // 	metaType=interface java.lang.annotation.Target; metaType=interface java.lang.annotation.Retention; metaType=interface java.lang.annotation.Documented; 
					if (isQualifier(metaType)) {
						foundMeta = true;
						// Only accept fallback match if @Qualifier annotation has a value...
						// Otherwise it is just a marker for a custom qualifier annotation.
						if ((fallbackToMeta && StringUtils.isEmpty(AnnotationUtils.getValue(metaAnn))) ||
								!checkQualifier(bdHolder, metaAnn, typeConverter)) {
							return false;
						}
					}
				}
				if (fallbackToMeta && !foundMeta) {
					return false;
				}
			}
		}
		return true;
	}

}

代码块36:checkQualifier

匹配名称

参数:bdHolder=Bean definition with name ‘zhangsan’ and aliases []: Root bean: class [null]; scope=singleton; abstract=false; …

package org.springframework.beans.factory.annotation;

public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwareAutowireCandidateResolver{

	protected boolean checkQualifier( //bdHolder=Bean definition with name 'zhangsan' and aliases []: Root bean: class [null]; scope=singleton; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=demoApplication; factoryMethodName=getUserInfo1; initMethodName=init; destroyMethodName=(inferred); defined in com.helloworld.DemoApplication;
			BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

		Class<? extends Annotation> type = annotation.annotationType(); //注释类型 	type=interface org.springframework.beans.factory.annotation.Qualifier; 
		RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

		AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName()); //获取bd定义上的  qualifier  候选
		if (qualifier == null) {
			qualifier = bd.getQualifier(ClassUtils.getShortName(type));
		}
		if (qualifier == null) {
			// First, check annotation on qualified element, if any
			Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type);
			// Then, check annotation on factory method, if applicable
			if (targetAnnotation == null) {
				targetAnnotation = getFactoryMethodAnnotation(bd, type);
			}
			if (targetAnnotation == null) {
				RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
				if (dbd != null) {
					targetAnnotation = getFactoryMethodAnnotation(dbd, type);
				}
			}
			if (targetAnnotation == null) {
				// Look for matching annotation on the target class
				if (getBeanFactory() != null) {
					try {
						Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName()); // 	beanType=class com.helloworld.entity.UserInfo; 
						if (beanType != null) {
							targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
						}
					}
					catch (NoSuchBeanDefinitionException ex) {
						// Not the usual case - simply forget about the type check...
					}
				}
				if (targetAnnotation == null && bd.hasBeanClass()) {
					targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
				}
			}
			if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
				return true;
			}
		}

		Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation); // 	attributes=value=zhangsan;; 
		if (attributes.isEmpty() && qualifier == null) {
			// If no attributes, the qualifier must be present
			return false;
		}
		for (Map.Entry<String, Object> entry : attributes.entrySet()) {
			String attributeName = entry.getKey(); // 	attributeName=value; 
			Object expectedValue = entry.getValue(); // 	expectedValue=zhangsan; 
			Object actualValue = null;
			// Check qualifier first
			if (qualifier != null) {
				actualValue = qualifier.getAttribute(attributeName);
			}
			if (actualValue == null) {
				// Fall back on bean definition attribute
				actualValue = bd.getAttribute(attributeName);
			}

			if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&

			"(36) 匹配名称"

			"参数:candidateName=zhangsan"

					expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
				// Fall back on bean name (or alias) match
				continue;
			}
			if (actualValue == null && qualifier != null) {
				// Fall back on default, but only if the qualifier is present
				actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
			}
			if (actualValue != null) {
				actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
			}
			if (!expectedValue.equals(actualValue)) {
				return false;
			}
		}
		return true;
	}

}

代码块37:matchesName

匹配名称

参数:candidateName=zhangsan

package org.springframework.beans.factory.config;

public class BeanDefinitionHolder implements BeanMetadataElement{

	public boolean matchesName(@Nullable String candidateName) { //candidateName=zhangsan;

		return (candidateName != null && (candidateName.equals(this.beanName) ||

		"(37) 匹配名称"

				candidateName.equals(BeanFactoryUtils.transformedBeanName(this.beanName)) ||
				ObjectUtils.containsElement(this.aliases, candidateName))); // 	true; 
	}

}

小结:调用栈

判断zhangsan与@Qualifier(“zhangsan”)的值"zhangsan"是否匹配

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  15. DefaultListableBeanFactory.resolveDependency()
  16. DefaultListableBeanFactory.doResolveDependency()
  17. *DefaultListableBeanFactory.findAutowireCandidates()
  18. *DefaultListableBeanFactory.isAutowireCandidate()
  19. *DefaultListableBeanFactory.isAutowireCandidate()
  20. *DefaultListableBeanFactory.isAutowireCandidate()
  21. *QualifierAnnotationAutowireCandidateResolver.isAutowireCandidate()
  22. *QualifierAnnotationAutowireCandidateResolver.checkQualifiers()
  23. *QualifierAnnotationAutowireCandidateResolver.checkQualifier()
  24. *BeanDefinitionHolder.matchesName()

匹配到zhangsan,将zhangsan添加到候选组件

将断点打到DefaultListableBeanFactory.addCandidateEntry方法,则代码执行过程如下

代码块38:findAutowireCandidates

添加候选人条目

参数:beanName=demoApplication

参数:requiredType=class com.helloworld.entity.UserInfo

参数:descriptor=field ‘userInfo’

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	protected Map<String, Object> findAutowireCandidates( //beanName=demoApplication;requiredType=class com.helloworld.entity.UserInfo;descriptor=field 'userInfo';
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {

		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
				this, requiredType, true, descriptor.isEager());
		"(26)"

				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=zhangsan; candidate=lisi; 
			if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { //3.1 如果不是自引用 && candidate有资格作为依赖注入的候选者
				addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中
			}
		}
		if (result.isEmpty()) { //如果结果为空,则返回需要更多的输入
			boolean multiple = indicatesMultipleBeans(requiredType); //如果依旧没找到,执行降级匹配 	multiple=false; 
			// Consider fallback matches if the first pass failed to find anything...
			DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); //4.1 使用降级匹配(跟正常匹配类似)
			for (String candidate : candidateNames) { //5.如果使用降级匹配结果还是空,则考虑自引用 	candidate=zhangsan; candidate=lisi; 
				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.如果使用降级匹配结果还是空,则考虑自引用 	candidate=zhangsan; candidate=lisi; 
					
							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) { // 	beanName=demoApplication; candidate=zhangsan; 

						addCandidateEntry(result, candidate, descriptor, requiredType); //&& candidate允许依赖注入,则将候选者添加到result中 	descriptor=field 'userInfo'; requiredType=class com.helloworld.entity.UserInfo; candidate=zhangsan; result=zhangsan=class com.helloworld.entity.UserInfo;; 

						"(38) 添加候选人条目"

						"参数:candidateName=zhangsan"
						"参数:descriptor=field 'userInfo'"
						"参数:requiredType=class com.helloworld.entity.UserInfo"

						"&& candidate允许依赖注入,则将候选者添加到result中 	descriptor=field 'userInfo'; requiredType=class com.helloworld.entity.UserInfo; candidate=zhangsan; result=zhangsan=class com.helloworld.entity.UserInfo;;"

					}
				}
			}
		}
		return result; // 	zhangsan=class com.helloworld.entity.UserInfo;; 
	}

}

代码块39:addCandidateEntry

添加候选组件

参数:candidateName=zhangsan

参数:descriptor=field ‘userInfo’

参数:requiredType=class com.helloworld.entity.UserInfo

package org.springframework.beans.factory.support;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{

	private void addCandidateEntry(Map<String, Object> candidates, String candidateName, //candidateName=zhangsan;descriptor=field 'userInfo';requiredType=class com.helloworld.entity.UserInfo;
			DependencyDescriptor descriptor, Class<?> requiredType) {

		if (descriptor instanceof MultiElementDescriptor) {
			Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); //这个时候直接从容器中去
			if (!(beanInstance instanceof NullBean)) {
				candidates.put(candidateName, beanInstance);
			}
		}
		else if (containsSingleton(candidateName) || (descriptor instanceof StreamDependencyDescriptor &&
				((StreamDependencyDescriptor) descriptor).isOrdered())) {
			Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); //这个时候直接从容器中去
			candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance));
		}
		else {

			candidates.put(candidateName, getType(candidateName)); //3.将beanName -> bean实例的类型 的映射添加到candidates(此时的value为bean实例的类型) 	candidateName=zhangsan; 

			"(39) 添加候选组件"

			"3.将beanName -> bean实例的类型 的映射添加到candidates(此时的value为bean实例的类型) 	candidateName=zhangsan;"

		}
	}

}

小结:调用栈

匹配到zhangsan,将zhangsan添加到候选组件

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  15. DefaultListableBeanFactory.resolveDependency()
  16. DefaultListableBeanFactory.doResolveDependency()
  17. *DefaultListableBeanFactory.findAutowireCandidates()
  18. *DefaultListableBeanFactory.addCandidateEntry()

实例化zhangsan

将断点打到DependencyDescriptor.resolveCandidate方法,则代码执行过程如下

代码块40:resolveCandidate

获取bean对象

参数:beanName=zhangsan

参数:requiredType=class com.helloworld.entity.UserInfo

参数: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=zhangsan;requiredType=class com.helloworld.entity.UserInfo;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,userServiceImpl,zhangsan,lisi,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy;
			throws BeansException {


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

		"(40) 获取bean对象"

		"直接从容器中获取真正的对象"

	}

}

小结:调用栈

实例化zhangsan

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  15. DefaultListableBeanFactory.resolveDependency()
  16. DefaultListableBeanFactory.doResolveDependency()
  17. *DependencyDescriptor.resolveCandidate()

此时demoApplication和zhangsan实例化完毕,执行依赖注入

将断点打到AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject方法,则代码执行过程如下

代码块41:inject

使用反射执行依赖注入

参数:beanName=demoApplication

参数: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=demoApplication;pvs=PropertyValues: length=0;
			Field field = (Field) this.member; //1.拿到该元数据的属性值 	field=private com.helloworld.entity.UserInfo com.helloworld.DemoApplication.userInfo; 
			Object value;
			if (this.cached) { //2.如果缓存中已经存在,则直接从缓存中解析属性
				value = resolvedCachedArgument(beanName, this.cachedFieldValue); //第一次注入的时候肯定没有缓存这里也是对原型情况的处理
			}
			else {
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required); //3.将field封装成DependencyDescriptor 	desc=field 'userInfo'; 
				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);
					"(23)"

				}
				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 'userInfo'; 
							registerDependentBeans(beanName, autowiredBeanNames); //7.注册依赖关系到缓存(beanName 依赖 autowiredBeanNames) 	autowiredBeanNames=zhangsan,; beanName=demoApplication; 
							if (autowiredBeanNames.size() == 1) { //8.如果属性依赖注入的bean只有一个(正常都是一个) 	autowiredBeanNames=zhangsan,; 
								String autowiredBeanName = autowiredBeanNames.iterator().next(); //自动注入的名称 	autowiredBeanName=zhangsan; 
								if (beanFactory.containsBean(autowiredBeanName) &&
										beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { // 	autowiredBeanName=zhangsan; 
									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.entity.UserInfo com.helloworld.DemoApplication.userInfo; 

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

				"(41) 使用反射执行依赖注入"

				"13.通过反射为属性赋值,将解析出来的bean实例赋值给field"

			}
		}

}

小结:调用栈

此时demoApplication和zhangsan实例化完毕,执行依赖注入

  1. DemoApplication.main()
  2. AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
  3. AbstractApplicationContext.refresh()
  4. AbstractApplicationContext.finishBeanFactoryInitialization()
  5. DefaultListableBeanFactory.preInstantiateSingletons()
  6. AbstractBeanFactory.getBean()
  7. AbstractBeanFactory.doGetBean()
  8. DefaultSingletonBeanRegistry.getSingleton()
  9. AbstractAutowireCapableBeanFactory.createBean()
  10. AbstractAutowireCapableBeanFactory.doCreateBean()
  11. AbstractAutowireCapableBeanFactory.populateBean()
  12. AutowiredAnnotationBeanPostProcessor.postProcessProperties()
  13. InjectionMetadata.inject()
  14. *AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值