3.springboot-@Autowired和@Value工作原理

1.简介

A.名词说明

  • spring bean生命周期
  • 复合构造函数(synthetic):由编译器引入的构造函数,主要用于JVM内部使用;
  • 桥接方法(bridge):由编译器引入的方法,主要用于JVM内部使用;

B.@Autowired与@Value功能

  • @Autowired与@Value功能基本相同,都可以自动装配bean;
  • @Value除了可以自动装配bean外,还可以自动装配配置参数。装配配置参数时,也可以配置参数写在方法上;
@Component
public class MyAutowiredDemo {
    @Value("user")
    public Object configInt;

    @Value("${spring.test.config-int}")
    public void test(Object configInt) {
        System.out.println(configInt);
    }
}

2.InjectionMetadata注入元数据

InjectionMetadata(类的注入元数据),描述每个依赖spring注入的java类,以及所有需要注入member(Member是java字段、方法和构造函数的父类)的相关信息;

//**类的注入元数据(描述每个依赖spring注入的java类,以及所有需要注入member的相关信息)
public class InjectionMetadata {

	//**空元数据
	public static final InjectionMetadata EMPTY = new InjectionMetadata(Object.class, Collections.emptyList()) {
		@Override
		protected boolean needsRefresh(Class clazz) {
			return false;
		}
		@Override
		public void checkConfigMembers(RootBeanDefinition beanDefinition) {
		}
		@Override
		public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) {
		}
		@Override
		public void clear(@Nullable PropertyValues pvs) {
		}
	};

    //**注入的目标类
	private final Class targetClass;
    //**目标类所有注入元素的集合
	private final Collection injectedElements;
    //**检查的注入元素集合
	@Nullable
	private volatile Set checkedElements;

    //**构造方法
	public InjectionMetadata(Class targetClass, Collection elements) {
		this.targetClass = targetClass;
		this.injectedElements = elements;
	}

    //**检查是否需要刷新
	protected boolean needsRefresh(Class clazz) {
		return this.targetClass != clazz;
	}
    
    //**遍历注入元素集合检查member是否注册到externallyManagedConfigMembers(spring管理的配置成员集合)
	public void checkConfigMembers(RootBeanDefinition beanDefinition) {
		Set checkedElements = new LinkedHashSet<>(this.injectedElements.size());
		for (InjectedElement element : this.injectedElements) {
		    //**如注入元素对应的member没有注册到externallyManagedConfigMembers,则注册
		    //**然后把注入元素添加到checkedElements
			Member member = element.getMember();
			if (!beanDefinition.isExternallyManagedConfigMember(member)) {
				beanDefinition.registerExternallyManagedConfigMember(member);
				checkedElements.add(element);
				if (logger.isTraceEnabled()) {
					logger.trace("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
				}
			}
		}
		this.checkedElements = checkedElements;
	}
    
    //**遍历注入元素集合,调用注入元素的inject方法注入member依赖的bean
	public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
		Collection checkedElements = this.checkedElements;
		Collection elementsToIterate =
				(checkedElements != null ? checkedElements : this.injectedElements);
		if (!elementsToIterate.isEmpty()) {
			for (InjectedElement element : elementsToIterate) {
				if (logger.isTraceEnabled()) {
					logger.trace("Processing injected element of bean '" + beanName + "': " + element);
				}
				element.inject(target, beanName, pvs);
			}
		}
	}

	//**遍历注入元素集合,调用注入元素的clearPropertySkipping方法清除所有已经注入的member
	public void clear(@Nullable PropertyValues pvs) {
		Collection checkedElements = this.checkedElements;
		Collection elementsToIterate =
				(checkedElements != null ? checkedElements : this.injectedElements);
		if (!elementsToIterate.isEmpty()) {
			for (InjectedElement element : elementsToIterate) {
				element.clearPropertySkipping(pvs);
			}
		}
	}

    //**静态方法,创建InjectionMetadata对象
	public static InjectionMetadata forElements(Collection elements, Class clazz) {
		return (elements.isEmpty() ? InjectionMetadata.EMPTY : new InjectionMetadata(clazz, elements));
	}

	//**静态方法,检查是否需要刷新
	public static boolean needsRefresh(@Nullable InjectionMetadata metadata, Class clazz) {
		return (metadata == null || metadata.needsRefresh(clazz));
	}

    //**注入元素(描述每个依赖spring注入的member相关信息)
	public abstract static class InjectedElement {
        //**member
		protected final Member member;
        //**member是否是字段
		protected final boolean isField;
        //**member的属性描述器
		@Nullable
		protected final PropertyDescriptor pd;
        //**是否跳过
		@Nullable
		protected volatile Boolean skip;
        
        //**构造方法
		protected InjectedElement(Member member, @Nullable PropertyDescriptor pd) {
			this.member = member;
			this.isField = (member instanceof Field);
			this.pd = pd;
		}
        
        //**获取member依赖spring注入的bean类型
		protected final Class getResourceType() {
		    //**如果是字段,则直接返回字段的类型
			if (this.isField) {
				return ((Field) this.member).getType();
			}
			//**如果包含属性描述器,则使用属性描述器获取类型
			else if (this.pd != null) {
				return this.pd.getPropertyType();
			}
			else {  //**如果是方法,则返回第一个参数的类型
				return ((Method) this.member).getParameterTypes()[0];
			}
		}
        
        //**检查指定类是否可以注入到member(指定类和member依赖bean是否存在继承关系)
		protected final void checkResourceType(Class resourceType) {
			if (this.isField) {
				Class fieldType = ((Field) this.member).getType();
				if (!(resourceType.isAssignableFrom(fieldType) || fieldType.isAssignableFrom(resourceType))) {
					throw new IllegalStateException("Specified field type [" + fieldType +
							"] is incompatible with resource type [" + resourceType.getName() + "]");
				}
			}
			else {
				Class paramType =
						(this.pd != null ? this.pd.getPropertyType() : ((Method) this.member).getParameterTypes()[0]);
				if (!(resourceType.isAssignableFrom(paramType) || paramType.isAssignableFrom(resourceType))) {
					throw new IllegalStateException("Specified parameter type [" + paramType +
							"] is incompatible with resource type [" + resourceType.getName() + "]");
				}
			}
		}

		//**注入member依赖的bean(实际没有使用,使用的其子类AutowiredFieldElement和AutowiredMethodElement的重写方法)
		protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
				throws Throwable {
            //**如果是字段,直接设置字段的值
			if (this.isField) {
				Field field = (Field) this.member;
				ReflectionUtils.makeAccessible(field);
				//**getResourceToInject(target, requestingBeanName)获取注入的bean
				field.set(target, getResourceToInject(target, requestingBeanName));
			}
			else {
			    //**如果已经注入,则跳过
				if (checkPropertySkipping(pvs)) {
					return;
				}
				//**如果是方法,调用方法
				try {
					Method method = (Method) this.member;
					ReflectionUtils.makeAccessible(method);
					//**getResourceToInject(target, requestingBeanName)获取注入的bean
					method.invoke(target, getResourceToInject(target, requestingBeanName));
				}
				catch (InvocationTargetException ex) {
					throw ex.getTargetException();
				}
			}
		}

		//**检查是否已经注入
		protected boolean checkPropertySkipping(@Nullable PropertyValues pvs) {
			Boolean skip = this.skip;
			if (skip != null) {
				return skip;
			}
			if (pvs == null) {
				this.skip = false;
				return false;
			}
			synchronized (pvs) {
				skip = this.skip;
				if (skip != null) {
					return skip;
				}
				if (this.pd != null) {
				    //**包含在已经处理过的集合(processedProperties)中,则返回true
					if (pvs.contains(this.pd.getName())) {
						this.skip = true;
						return true;
					}
					//**否则,在已经处理过的集合中注册,并返回false
					else if (pvs instanceof MutablePropertyValues) {
						((MutablePropertyValues) pvs).registerProcessedProperty(this.pd.getName());
					}
				}
				this.skip = false;
				return false;
			}
		}

		//**清除已经注入的member
		protected void clearPropertySkipping(@Nullable PropertyValues pvs) {
			if (pvs == null) {
				return;
			}
			synchronized (pvs) {
				if (Boolean.FALSE.equals(this.skip) && this.pd != null && pvs instanceof MutablePropertyValues) {
					((MutablePropertyValues) pvs).clearProcessedProperty(this.pd.getName());
				}
			}
		}

		//**获取注入的对象,这里返回null,需用子类实现
		@Nullable
		protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
			return null;
		}

        ...equals and hashCode and toString方法
	}
}

3.AutowiredAnnotationBeanPostProcessor(自动装配处理器)

注意(重点)

A.处理逻辑

  • 首先处理@Lookup注解并获取候选的构造函数(包括父类上的@Lookup)。注意,这里只是选择了匹配的构造函数,有可能有多个,具体调用哪个构造函数逻辑在ConstructorResolver.autowireConstructor(),不在本篇深究;
  • 然后把依赖spring注入的member信息注册到RootBeanDefinition的externallyManagedConfigMembers(spring管理的配置成员集合);
  • 最后把bean及其依赖注入的bean的关系注册到DefaultSingletonBeanRegistryt的dependentBeanMap和dependenciesForBeanMap。然后设置注入的值(如果是字段,直接赋值,如果是方法,调用方法);

B.自定义自动装配注解

自定一个自动装配注解@MyAutowired,功能同解@Autowired

//1.自定义解@MyAutowired注解
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAutowired {

    //**required参数名也可以自定义
    boolean required() default true;

}

//2.使MyAutowired注解生效
@Component
public class MyAutowiredAnnotationBeanPostProcessor extends AutowiredAnnotationBeanPostProcessor {

    public MyAutowiredAnnotationBeanPostProcessor(){
        super.setAutowiredAnnotationTypes(Set.of(Autowired.class, Value.class, MyAutowired.class));
    }
}

//3.使用示例
@Component
public class MyAutowiredDemo {

    @MyAutowired
    private User user;

    public void hello(){
        System.out.println(user.getClass());
    }
}

C.处理规则

构造方法注入:

  • 如果required=true,只能标注一个@Autowired
  • 如果required=false,可标注多个@Autowired,且匹配项最多的构造函数会生效
  • 如果没有匹配到任何一个构造函数,则默认的构造函数会生效
  • 如果只有一个构造函数,则这个构造函数会生效(无论有没有标注@Autowired)
  • 构造函数不需要为public

字段注入:

  • 字段在构造方法注入之后,在配置方法注入之前调用
  • 字段不需要为public

方法注入

  • 配置方法可以有任意名称和任意数量的参数,spring会从容器中匹配并注入这些参数
  • setter方法是配置方法的特例,spring并没有要求配置方法一定是setter方法
  • 配置方法不需要为public

xml配置注入

  • 默认情况下,AutowiredAnnotationBeanPostProcessor会注册context:annotation-config和context:component-scan标签
  • 可指定自定义的AutowiredAnnotationBeanPostProcessor删除或者关闭默认的注解配置
  • 注意:注解注入会在xml注入之前执行。后一种配置会覆盖前一种配置

Lookup方法

  • @Lookup会在运行查找需要注入的参数(如果参数不是单例的,这会很有用。等同类型安全的getBean方法)

源码

  • InstantiationAwareBeanPostProcessorAdapter:SmartInstantiationAwareBeanPostProcessor(智能实例化处理器)接口适配器(空实现),其子类只需要实现关注的方法,而不用把所有的方法都实现;
  • MergedBeanDefinitionPostProcessor:合并Bean定义后置处理器;
  • PriorityOrdered:优先的Ordered序列,PriorityOrdered优先级总是在Ordered之前(无论order值是多少);
  • BeanFactoryAware:获取spring上下文中的BeanFactory;
  • 执行顺序:
    • BeanFactory.setBeanFactory()
    • PriorityOrdered.getOrder()
    • InstantiationAwareBeanPostProcessorAdapter.determineCandidateConstructors():处理@Lookup注解并获取候选的构造函数(包括父类上的@Lookup);
    • MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition():注册需要注入的member;
    • InstantiationAwareBeanPostProcessorAdapter.postProcessProperties():执行注入bean的逻辑(包括父类上的注入注解);
    • MergedBeanDefinitionPostProcessor.resetBeanDefinition():重置bean定义后,在缓存中删除注入数据;
/**
 * 实现自动装配:注解,字段,setter方法和配置方法
 * 通过注解检测需要注入的成员。默认注解包括@Autowired和@Value,并且支持JSR-330的@Inject(同@Autowired)
 * 
 * 构造方法注入:
 * 如果required=true,只能标注一个@Autowired
 * 如果required=false,可标注多个@Autowired,且匹配项最多的构造函数会生效
 * 如果没有匹配到任何一个构造函数,则默认的构造函数会生效
 * 如果只有一个构造函数,则这个构造函数会生效(无论有没有标注@Autowired)
 * 构造函数不需要为public
 *
 * 字段注入:
 * 字段在构造方法注入之后,在配置方法注入之前调用
 * 字段不需要为public
 *
 * 方法注入
 * 配置方法可以有任意名称和任意数量的参数,spring会从容器中匹配并注入这些参数
 * setter方法是配置方法的特例,spring并没有要求配置方法一定是setter方法
 * 配置方法不需要为public
 *
 * xml配置注入
 * 默认情况下,AutowiredAnnotationBeanPostProcessor会注册context:annotation-config和context:component-scan标签
 * 可指定自定义的AutowiredAnnotationBeanPostProcessor删除或者关闭默认的注解配置
 *
 * 注意:注解注入会在xml注入之前执行。后一种配置会覆盖前一种配置
 *
 * Lookup方法
 * @Lookup会在运行查找需要注入的参数(如果参数不是单例的,这会很有用。等同类型安全的getBean方法)
 */
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
	//**处理的注入注解
	private final Set> autowiredAnnotationTypes = new LinkedHashSet<>(4);
    //**表示required参数的参数名
	private String requiredParameterName = "required";
    //**表示required参数的默认值
	private boolean requiredParameterValue = true;
    //**默认的执行顺序
	private int order = Ordered.LOWEST_PRECEDENCE - 2;
    //**beanFactory
	@Nullable
	private ConfigurableListableBeanFactory beanFactory;
    //**缓存处理过@Lookup注解的bean名称
	private final Set lookupMethodsChecked = Collections.newSetFromMap(new ConcurrentHashMap<>(256));
    //**缓存指定类候选的构造函数
	private final Map, Constructor[]> candidateConstructorsCache = new ConcurrentHashMap<>(256);
    //**缓存注入的元数据
	private final Map injectionMetadataCache = new ConcurrentHashMap<>(256);

    //**默认处理的自动装配注解为@Autowired和@Value,并且支持@Inject
	public AutowiredAnnotationBeanPostProcessor() {
		this.autowiredAnnotationTypes.add(Autowired.class);
		this.autowiredAnnotationTypes.add(Value.class);
		try {
			this.autowiredAnnotationTypes.add((Class)
					ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
			logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
		}
		catch (ClassNotFoundException ex) {
			// JSR-330 API not available - simply skip.
		}
	}
    
    //**指定处理的自动装配注解
	public void setAutowiredAnnotationType(Class autowiredAnnotationType) {
		Assert.notNull(autowiredAnnotationType, "'autowiredAnnotationType' must not be null");
		this.autowiredAnnotationTypes.clear();
		this.autowiredAnnotationTypes.add(autowiredAnnotationType);
	}

	//**指定多个处理的自动装配注解
	public void setAutowiredAnnotationTypes(Set> autowiredAnnotationTypes) {
		Assert.notEmpty(autowiredAnnotationTypes, "'autowiredAnnotationTypes' must not be empty");
		this.autowiredAnnotationTypes.clear();
		this.autowiredAnnotationTypes.addAll(autowiredAnnotationTypes);
	}

	//**指定表示required参数的参数名
	public void setRequiredParameterName(String requiredParameterName) {
		this.requiredParameterName = requiredParameterName;
	}

	//**指定表示required参数的参数值
	public void setRequiredParameterValue(boolean requiredParameterValue) {
		this.requiredParameterValue = requiredParameterValue;
	}

    //**设置执行顺序
	public void setOrder(int order) {
		this.order = order;
	}
    
    //**实现PriorityOrdered,获取执行顺序
	@Override
	public int getOrder() {
		return this.order;
	}

    //**实现BeanFactoryAware,获取beanFactory
	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
			throw new IllegalArgumentException(
					"AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory: " + beanFactory);
		}
		this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
	}

    //**实现MergedBeanDefinitionPostProcessor
    //**如果存在需要注入的member,则注册到externallyManagedConfigMembers(spring管理的配置成员集合)
	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) {
	    //**获取注入元数据
		InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
		//**如果存在需要注入的member,把注入元素注册到externallyManagedConfigMembers(spring管理的配置成员集合)
		metadata.checkConfigMembers(beanDefinition);
	}
    
    //**实现MergedBeanDefinitionPostProcessor,重置bean定义后,在缓存中删除注入数据;
	@Override
	public void resetBeanDefinition(String beanName) {
		this.lookupMethodsChecked.remove(beanName);
		this.injectionMetadataCache.remove(beanName);
	}
    
    //**实现InstantiationAwareBeanPostProcessorAdapter,处理@Lookup注解并获取候选的构造函数
    //**如果required=true,则只能有一个候选构造函数
    //**如果required=false,则全部都为候选构造函数
    //**如果只有一个构造函数且包含参数,则这个构造函数为候选构造函数(无论有没有标注@Autowired)
	@Override
	@Nullable
	public Constructor[] determineCandidateConstructors(Class beanClass, final String beanName)
			throws BeanCreationException {
        //**处理当前类及其父类@Lookup注解(spring会动态生成子类并重写/实现被注解的方法),并缓存到lookupMethodsChecked中
		if (!this.lookupMethodsChecked.contains(beanName)) {
			if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
				try {
					Class targetClass = beanClass;
					do {
						ReflectionUtils.doWithLocalMethods(targetClass, method -> {
							Lookup lookup = method.getAnnotation(Lookup.class);
							if (lookup != null) {
								Assert.state(this.beanFactory != null, "No BeanFactory available");
								LookupOverride override = new LookupOverride(method, lookup.value());
								try {
									RootBeanDefinition mbd = (RootBeanDefinition)
											this.beanFactory.getMergedBeanDefinition(beanName);
									mbd.getMethodOverrides().addOverride(override);
								}
								catch (NoSuchBeanDefinitionException ex) {
									throw new BeanCreationException(beanName,
											"Cannot apply @Lookup to beans without corresponding bean definition");
								}
							}
						});
						targetClass = targetClass.getSuperclass();
					}
					while (targetClass != null && targetClass != Object.class);

				}
				catch (IllegalStateException ex) {
					throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
				}
			}
			this.lookupMethodsChecked.add(beanName);
		}

		//**从缓存中获取当前类的候选构造函数
		Constructor[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
		//**缓存中不存在,则获取
		if (candidateConstructors == null) {
			//**加锁
			synchronized (this.candidateConstructorsCache) {
				candidateConstructors = this.candidateConstructorsCache.get(beanClass);
				if (candidateConstructors == null) {
				    
				    //**获取所有构造函数
					Constructor[] rawCandidates;
					try {
						rawCandidates = beanClass.getDeclaredConstructors();
					}
					catch (Throwable ex) {
						throw new BeanCreationException(beanName,
								"Resolution of declared constructors on bean Class [" + beanClass.getName() +
								"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
					}
					//**存放候选构造函数
					List> candidates = new ArrayList<>(rawCandidates.length);
					//**required=true的构造函数
					Constructor requiredConstructor = null;
					//**默认的无参构造函数
					Constructor defaultConstructor = null;
					//**Kotlin中的primary构造函数,java直接返回null
					Constructor primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
					//**非Synthetic构造函数的数量(synthetic是由编译器引入的构造函数,主要用于JVM内部使用)
					int nonSyntheticConstructors = 0;
					
					//**遍历所有构造函数
					for (Constructor candidate : rawCandidates) {
					    //**记录非Synthetic构造函数的数量
						if (!candidate.isSynthetic()) {
							nonSyntheticConstructors++;
						}
						//**java这里为null
						else if (primaryConstructor != null) {
							continue;
						}
						//**查找是否包含@Autowired和@Value等注入注解
						MergedAnnotation ann = findAutowiredAnnotation(candidate);
						//**如果不包含注入注解,则获取当前类的用户类(如果当前类为spring生成的动态代理类,则会获取到当前类代理的类)构造函数的注入注解
						if (ann == null) {
							Class userClass = ClassUtils.getUserClass(beanClass);
							if (userClass != beanClass) {
								try {
									Constructor superCtor =
											userClass.getDeclaredConstructor(candidate.getParameterTypes());
									ann = findAutowiredAnnotation(superCtor);
								}
								catch (NoSuchMethodException ex) {
									// Simply proceed, no equivalent superclass constructor found...
								}
							}
						}
						
						//**如果包含注入注解,验证如果required=true时只能标注一个@Autowired,并添加到候选构造函数集合中
						if (ann != null) {
							if (requiredConstructor != null) {
								throw new BeanCreationException(beanName,
										"Invalid autowire-marked constructor: " + candidate +
										". Found constructor with 'required' Autowired annotation already: " +
										requiredConstructor);
							}
							//**获取当前构造函数required的值
							boolean required = determineRequiredStatus(ann);
							if (required) {
								if (!candidates.isEmpty()) {
									throw new BeanCreationException(beanName,
											"Invalid autowire-marked constructors: " + candidates +
											". Found constructor with 'required' Autowired annotation: " +
											candidate);
								}
								requiredConstructor = candidate;
							}
							candidates.add(candidate);
						}
						else if (candidate.getParameterCount() == 0) { //**否则如果参数为0,则为默认构造函数
							defaultConstructor = candidate;
						}
					}
					
					//**如果候选构造函数不为空,并且required=true的构造函数为空,则把默认构造函数添加到候选构造函数集合中
					if (!candidates.isEmpty()) {
						if (requiredConstructor == null) {
							if (defaultConstructor != null) {
								candidates.add(defaultConstructor);
							}
							else if (candidates.size() == 1 && logger.isInfoEnabled()) {
								logger.info("Inconsistent constructor declaration on bean with name '" + beanName +
										"': single autowire-marked constructor flagged as optional - " +
										"this constructor is effectively required since there is no " +
										"default constructor to fall back to: " + candidates.get(0));
							}
						}
						candidateConstructors = candidates.toArray(new Constructor[0]);
					}
				    //**如果只有一个构造函数,则这个构造函数会生效(无论有没有标注@Autowired)
					else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
						candidateConstructors = new Constructor[] {rawCandidates[0]};
					}
					//**针对Kotlin中的primary构造函数
					else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
							defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
						candidateConstructors = new Constructor[] {primaryConstructor, defaultConstructor};
					}
					else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
						candidateConstructors = new Constructor[] {primaryConstructor};
					}
					else { //**否则返回空构造函数数组
						candidateConstructors = new Constructor[0];
					}
					//**缓存到candidateConstructorsCache中
					this.candidateConstructorsCache.put(beanClass, candidateConstructors);
				}
			}
		}
		return (candidateConstructors.length > 0 ? candidateConstructors : null);
	}
    
    //**实现InstantiationAwareBeanPostProcessorAdapter.postProcessProperties(),执行注入bean的逻辑
	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
	    //**获取当前bean的注入元数据
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
		try {//**执行注入(字段使用使用AutowiredFieldElement.inject(),方法使用AutowiredMethodElement的.inject())
			metadata.inject(bean, beanName, pvs);
		}
		catch (BeanCreationException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
		}
		return pvs;
	}
    
    //**过时,以postProcessProperties为准
	@Deprecated
	@Override
	public PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {

		return postProcessProperties(pvs, bean, beanName);
	}

	//**指定bean的注入,逻辑基本和postProcessProperties一样,运行项目没发现有调用
	public void processInjection(Object bean) throws BeanCreationException {
		Class clazz = bean.getClass();
		InjectionMetadata metadata = findAutowiringMetadata(clazz.getName(), clazz, null);
		try {
			metadata.inject(bean, null, null);
		}
		catch (BeanCreationException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					"Injection of autowired dependencies failed for class [" + clazz + "]", ex);
		}
	}

    //**获取指定bean的注入元数据
	private InjectionMetadata findAutowiringMetadata(String beanName, Class clazz, @Nullable PropertyValues pvs) {
		// Fall back to class name as cache key, for backwards compatibility with custom callers.
		String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
		//**从缓存中获取注入元数据
		InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
		//**如果metadata为空,则重新构造metadata,如果metadata的目标类不是传入的clazz,则清除注入数据,然后重新构造metadata
		if (InjectionMetadata.needsRefresh(metadata, clazz)) {
			synchronized (this.injectionMetadataCache) {
				metadata = this.injectionMetadataCache.get(cacheKey);
				if (InjectionMetadata.needsRefresh(metadata, clazz)) {
					if (metadata != null) {
						metadata.clear(pvs);
					}
					//**构造metadata
					metadata = buildAutowiringMetadata(clazz);
					//**缓存到injectionMetadataCache中
					this.injectionMetadataCache.put(cacheKey, metadata);
				}
			}
		}
		return metadata;
	}

    //**构造指定类及其父类的注入元数据
	private InjectionMetadata buildAutowiringMetadata(final Class clazz) {
	    //**如果不包含注入注解,则返回空注入元数据
		if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {
			return InjectionMetadata.EMPTY;
		}
        //**存放类的所有注入元素
		List elements = new ArrayList<>();
		Class targetClass = clazz;
        
        //**遍历获取类及其父类的注入元素
		do {
			final List currElements = new ArrayList<>();
            
            //**遍历获取类的字段注入元素
			ReflectionUtils.doWithLocalFields(targetClass, field -> {
				MergedAnnotation ann = findAutowiredAnnotation(field);
				if (ann != null) {
				    //**不支持静态字段
					if (Modifier.isStatic(field.getModifiers())) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation is not supported on static fields: " + field);
						}
						return;
					}
					//**获取required的值
					boolean required = determineRequiredStatus(ann);
					//**创建注入元素并存放到currElements中
					currElements.add(new AutowiredFieldElement(field, required));
				}
			});

            //**遍历获取类的方法注入元素
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
			    //**如果方法是编译器引入桥接方法,则跳过
				Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
				if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
					return;
				}
				
				MergedAnnotation ann = findAutowiredAnnotation(bridgedMethod);
				//**如果方法包含注入注解 && 属于指定clazz类(继承的方法也算)
				if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
				    //**不支持静态方法
					if (Modifier.isStatic(method.getModifiers())) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation is not supported on static methods: " + method);
						}
						return;
					}
					//**没有参数,则跳过
					if (method.getParameterCount() == 0) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation should only be used on methods with parameters: " +
									method);
						}
					}
					//**获取required的值
					boolean required = determineRequiredStatus(ann);
					//**获取方法的属性描述器
					PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
					//**创建注入元素并存放到currElements中
					currElements.add(new AutowiredMethodElement(method, required, pd));
				}
			});

			elements.addAll(0, currElements);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);
        
        //**创建注入元数据
		return InjectionMetadata.forElements(elements, clazz);
	}
    
    //**查找member上的注入注解
	@Nullable
	private MergedAnnotation findAutowiredAnnotation(AccessibleObject ao) {
		MergedAnnotations annotations = MergedAnnotations.from(ao);
		for (Class type : this.autowiredAnnotationTypes) {
			MergedAnnotation annotation = annotations.get(type);
			if (annotation.isPresent()) {
				return annotation;
			}
		}
		return null;
	}

	//**获取注入配置的required的值
	@SuppressWarnings({"deprecation", "cast"})
	protected boolean determineRequiredStatus(MergedAnnotation ann) {
		// The following (AnnotationAttributes) cast is required on JDK 9+.
		return determineRequiredStatus((AnnotationAttributes)
				ann.asMap(mergedAnnotation -> new AnnotationAttributes(mergedAnnotation.getType())));
	}

	//**过时,获取注入配置的required的值
	@Deprecated
	protected boolean determineRequiredStatus(AnnotationAttributes ann) {
		return (!ann.containsKey(this.requiredParameterName) ||
				this.requiredParameterValue == ann.getBoolean(this.requiredParameterName));
	}

	//**根据类对象查找注入的候选bean
	protected  Map findAutowireCandidates(Class type) throws BeansException {
		if (this.beanFactory == null) {
			throw new IllegalStateException("No BeanFactory configured - " +
					"override the getBeanOfType method or specify the 'beanFactory' property");
		}
		return BeanFactoryUtils.beansOfTypeIncludingAncestors(this.beanFactory, type);
	}

	//**注册bean及其依赖注入的bean
	private void registerDependentBeans(@Nullable String beanName, Set autowiredBeanNames) {
		if (beanName != null) {
			for (String autowiredBeanName : autowiredBeanNames) {
				if (this.beanFactory != null && this.beanFactory.containsBean(autowiredBeanName)) {
					this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Autowiring by type from bean name '" + beanName +
							"' to bean named '" + autowiredBeanName + "'");
				}
			}
		}
	}

	//**解析指定的缓存方法参数/字段值
	@Nullable
	private Object resolvedCachedArgument(@Nullable String beanName, @Nullable Object cachedArgument) {
		if (cachedArgument instanceof DependencyDescriptor) {
			DependencyDescriptor descriptor = (DependencyDescriptor) cachedArgument;
			Assert.state(this.beanFactory != null, "No BeanFactory available");
			return this.beanFactory.resolveDependency(descriptor, beanName, null, null);
		}
		else {
			return cachedArgument;
		}
	}

    //**注入元素(描述每个依赖spring注入的字段相关信息)
	private class AutowiredFieldElement extends InjectionMetadata.InjectedElement {
        //**required
		private final boolean required;
        //**是否已经缓存字段注入的值
		private volatile boolean cached = false;
        //**缓存字段注入的值
		@Nullable
		private volatile Object cachedFieldValue;

		public AutowiredFieldElement(Field field, boolean required) {
			super(field, null);
			this.required = required;
		}
        
        //**注入
		@Override
		protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
			Field field = (Field) this.member;
			Object value;
			if (this.cached) {  //**如果已经缓存字段注入的值,则直接从缓存中解析
				value = resolvedCachedArgument(beanName, this.cachedFieldValue);
			}
			else {
			    //**获取注入的bean
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
				desc.setContainingClass(bean.getClass());
				Set autowiredBeanNames = new LinkedHashSet<>(1);
				Assert.state(beanFactory != null, "No BeanFactory available");
				TypeConverter typeConverter = beanFactory.getTypeConverter();
				try {
				    //**如果是@value获取配置的参数值,则此处获取的是配置的值,autowiredBeanNames会为空
					value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
				}
				catch (BeansException ex) {
					throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
				}
				synchronized (this) {  //**同步
					if (!this.cached) {
						if (value != null || this.required) { //**如果注入的bean存在 || required = true
							this.cachedFieldValue = desc;  //**缓存注入的bean
							//**注册bean及其依赖注入的bean
							registerDependentBeans(beanName, autowiredBeanNames); 
							//**如果匹配的依赖bean只有一个,则封装为ShortcutDependencyDescriptor,并缓存
							if (autowiredBeanNames.size() == 1) {
								String autowiredBeanName = autowiredBeanNames.iterator().next();
								if (beanFactory.containsBean(autowiredBeanName) &&
										beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
									this.cachedFieldValue = new ShortcutDependencyDescriptor(
											desc, autowiredBeanName, field.getType());
								}
							}
						}
						else {
							this.cachedFieldValue = null;
						}
						this.cached = true;
					}
				}
			}
			//**通过反射赋值
			if (value != null) {
				ReflectionUtils.makeAccessible(field);
				field.set(bean, value);
			}
		}
	}

	//**注入元素(描述每个依赖spring注入的方法相关信息)
	private class AutowiredMethodElement extends InjectionMetadata.InjectedElement {
        //**required
		private final boolean required;
        //**是否已经缓存方法注入的值
		private volatile boolean cached = false;
        //**缓存方法注入的值
		@Nullable
		private volatile Object[] cachedMethodArguments;

		public AutowiredMethodElement(Method method, boolean required, @Nullable PropertyDescriptor pd) {
			super(method, pd);
			this.required = required;
		}
        
        //**注入
		@Override
		protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
		    //**如果已经注入,则跳过
			if (checkPropertySkipping(pvs)) {
				return;
			}
			Method method = (Method) this.member;
			Object[] arguments;
			if (this.cached) {//**如果已经缓存方法注入的值,则直接从缓存中解析
				arguments = resolveCachedArguments(beanName);
			}
			else {
				int argumentCount = method.getParameterCount();
				arguments = new Object[argumentCount];
				DependencyDescriptor[] descriptors = new DependencyDescriptor[argumentCount];
				Set autowiredBeans = new LinkedHashSet<>(argumentCount);
				Assert.state(beanFactory != null, "No BeanFactory available");
				TypeConverter typeConverter = beanFactory.getTypeConverter();
				//**遍历方法的所有参数,获取注入的bean
				for (int i = 0; i < arguments.length; i++) {
					MethodParameter methodParam = new MethodParameter(method, i);
					DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
					currDesc.setContainingClass(bean.getClass());
					descriptors[i] = currDesc;
					try {
					    //**如果是@value获取配置的参数值,则此处获取的是配置的值,autowiredBeanNames会为空
						Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
						if (arg == null && !this.required) {
							arguments = null;
							break;
						}
						arguments[i] = arg;
					}
					catch (BeansException ex) {
						throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex);
					}
				}
				synchronized (this) {//**同步
					if (!this.cached) {
						if (arguments != null) {
							DependencyDescriptor[] cachedMethodArguments = Arrays.copyOf(descriptors, arguments.length);
							//**注册bean及其依赖注入的bean
							registerDependentBeans(beanName, autowiredBeans);
							//**如果每个参数匹配的依赖bean都只有一个,则封装为ShortcutDependencyDescriptor,并缓存
							if (autowiredBeans.size() == argumentCount) {
								Iterator it = autowiredBeans.iterator();
								Class[] paramTypes = method.getParameterTypes();
								for (int i = 0; i < paramTypes.length; i++) {
									String autowiredBeanName = it.next();
									if (beanFactory.containsBean(autowiredBeanName) &&
											beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
										cachedMethodArguments[i] = new ShortcutDependencyDescriptor(
												descriptors[i], autowiredBeanName, paramTypes[i]);
									}
								}
							}
							this.cachedMethodArguments = cachedMethodArguments;
						}
						else {
							this.cachedMethodArguments = null;
						}
						this.cached = true;
					}
				}
			}
			if (arguments != null) {
				try {//**通过反射调用方法
					ReflectionUtils.makeAccessible(method);
					method.invoke(bean, arguments);
				}
				catch (InvocationTargetException ex) {
					throw ex.getTargetException();
				}
			}
		}
        
        //**遍历解析缓存参数
		@Nullable
		private Object[] resolveCachedArguments(@Nullable String beanName) {
			Object[] cachedMethodArguments = this.cachedMethodArguments;
			if (cachedMethodArguments == null) {
				return null;
			}
			Object[] arguments = new Object[cachedMethodArguments.length];
			for (int i = 0; i < arguments.length; i++) {
				arguments[i] = resolvedCachedArgument(beanName, cachedMethodArguments[i]);
			}
			return arguments;
		}
	}

    //**注入依赖描述器
	@SuppressWarnings("serial")
	private static class ShortcutDependencyDescriptor extends DependencyDescriptor {

		private final String shortcut;

		private final Class requiredType;

		public ShortcutDependencyDescriptor(DependencyDescriptor original, String shortcut, Class requiredType) {
			super(original);
			this.shortcut = shortcut;
			this.requiredType = requiredType;
		}

		@Override
		public Object resolveShortcut(BeanFactory beanFactory) {
			return beanFactory.getBean(this.shortcut, this.requiredType);
		}
	}

}

你可能感兴趣的:(#,springboot配置,java,spring,boot,Autowired,Value,依赖注入)