探索Spring - @Autowired注入原理分析

水平有限,写博客更多是对自己学习的一种记录,哪块知识理解有误欢迎您留言指点,感激不尽!

疑问:

  1. @Autowired什么时候注入?
  2. @Autowired怎么注入?
  3. 运行流程是什么?

开始探索:

@Autowired实现类:

先看关于@Autowired的三张图片:
探索Spring - @Autowired注入原理分析_第1张图片
探索Spring - @Autowired注入原理分析_第2张图片探索Spring - @Autowired注入原理分析_第3张图片

  1. 根据@Autowired的@see提示找到AutowiredAnnotationBeanPostProcessor类,从注释可以看出是BeanPostProcessor是实现了自动注入的关键。是通过@Autowired跟@Value来检测哪些需要要注入。
  2. 该类继承了【InstantiationAwareBeanPostProcessorAdapter
    实现了【MergedBeanDefinitionPostProcessor
    这俩类先不进行分析,多读几遍,在refresh()中的registerBeanPostProcessors()丶finishBeanFactoryInitialization()中会用到这两个类
refresh()方法:

IOC的核心方法不用说就是refresh()了,我们就从这个方法开始入手(如果不知道refresh()方法,建议先去了解一下)。
探索Spring - @Autowired注入原理分析_第4张图片

标红的方法为实现@Autowired自动注入的关键方法:registerBeanPostProcessors与finishBeanFactoryInitialization下面对这俩方法进行具体分析。

registerBeanPostProcessors:

看方法名是不是很熟悉?之前@Autowired的实现类(AutowiredAnnotationBeanPostProcessor)就是实现了BeanPostProcessor,我们@Autowired的实现类将在这里进行注册,是在初始化所有bean之前执行。

【PostProcessorRegistrationDelegate类】
public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
     
        //  1.找到BeanPostProcessor的子类
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
	    
	     ...(其它代码省略)
		
		// 2.从子类postProcessorNames里找到实现MergedBeanDefinitionPostProcessor的子类,其中就包含AutowiredAnnotationBeanPostProcessor类。
		List internalPostProcessors = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}
	    ...
	     // 3.在这被注册
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);
	}
	
	// 4. registerBeanPostProcessors方法调到addBeanPostProcessor方法
【AbstractBeanFactory类】
	public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
	     ...
	     // 5.将BeanPostProcessor放到beanPostProcessors中,供后续程序调用。
		this.beanPostProcessors.add(beanPostProcessor);
	}

以上就是注册AutowiredAnnotationBeanPostProcessor的流程:
1.找到BeanPostProcessor的子类
2.找到MergedBeanDefinitionPostProcessor子类
3.放到beanPostProcessors中供后续使用

finishBeanFactoryInitialization

【AbstractApplicationContext类】
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	    ...
        // 1. 实例化所有非懒加载的单例
		beanFactory.preInstantiateSingletons();
	}

【DefaultListableBeanFactory类】
public void preInstantiateSingletons() throws BeansException {
	// 2.获取beanName的集合,beanDefinitionNames是在refresh()中的invokeBeanFactoryPostProcessors()中定义好的。
	  List beanNames = new ArrayList<>(this.beanDefinitionNames);
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				...
				}
				else {
				// 3. 根据beanName获取bean
					getBean(beanName);
				}
			}
		}
		...
	}

   // 4. 通过getBean() -> doGetBean() 
   【AbstractBeanFactory类】
protected  T doGetBean(final String name, @Nullable final Class requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
			...
			try {
			         ...
				if (mbd.isSingleton()) {
				   // 5. 通过beanName去缓存里找,有就返回,没有就执行第6步
					sharedInstance = getSingleton(beanName, () -> {
						try {
						// 6. 执行createBean,创建bean 
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
						...
						}
				 	 ...
				}
			}
			catch (BeansException ex) {
				...	
			}
		return (T) bean;
	}

【AbstractAutowireCapableBeanFactory类】
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {
	try {
        ...
      		// 7. 真正创建bean的方法
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			...
			return beanInstance;
		}
	}
	
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException {
    ...
	synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
				// 8. 这个方法会调用到AutowiredAnnotationBeanPostProcessor,这里并不会进行注入,只是定义哪些类的哪些属性需要注入。
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}
   ...
	try {
	       // 9. 填充Bean
			populateBean(beanName, mbd, instanceWrapper);
			// 10. 实例化Bean
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		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);
			}
		}

关键的方法是第8步跟第9步
分析applyMergedBeanDefinitionPostProcessors:

【AutowiredAnnotationBeanPostProcessor】类

	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) {
	   // 找到需要需要的属性,并封装成InjectMetadata
		InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
	  //  这里会对InjectionMetadata的checkedElements属性赋值,之后在注入的时候会用到
		metadata.checkConfigMembers(beanDefinition);
	}
	
	
	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());
		// Quick check on the concurrent map first, with minimal locking.
		InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
		if (InjectionMetadata.needsRefresh(metadata, clazz)) {
			synchronized (this.injectionMetadataCache) {
				metadata = this.injectionMetadataCache.get(cacheKey);
				if (InjectionMetadata.needsRefresh(metadata, clazz)) {
					if (metadata != null) {
						metadata.clear(pvs);
					}
					// 创建InjectionMetadata实例
					metadata = buildAutowiringMetadata(clazz);
					this.injectionMetadataCache.put(cacheKey, metadata);
				}
			}
		}
		return metadata;
	}
	
	private InjectionMetadata buildAutowiringMetadata(final Class clazz) {
		List elements = new ArrayList<>();
		Class targetClass = clazz;
		// do while获取需要注入的属性,封装成InjectionMetadata
		do {
			final List currElements = new ArrayList<>();

			ReflectionUtils.doWithLocalFields(targetClass, field -> {
			  // 这里会找到被@Autowired 跟@Value标注的字段
				AnnotationAttributes 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;
					}
					boolean required = determineRequiredStatus(ann);
					// 将对应的field封装到InjectedElement的Member上,
					   之后会用到filed进行属性注入
					currElements.add(new AutowiredFieldElement(field, required));
				}
			});

			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
				Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
				if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
					return;
				}
				AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
				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);
						}
					}
					boolean required = determineRequiredStatus(ann);
					PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
					currElements.add(new AutowiredMethodElement(method, required, pd));
				}
			});

			elements.addAll(0, currElements);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);

		return new InjectionMetadata(clazz, elements);
	}

applyMergedBeanDefinitionPostProcessors方法:
1.循环beanPostProcessors(registerBeanPostProcessors中注册的),找到实现了MergedBeanDefinitionPostProcessor的类,然后调用postProcessMergedBeanDefinition方法
2.postProcessMergedBeanDefinition方法中的findAutowiringMetadata方法,会找到被@Autowired修饰的字段,封装成InjectionMetadata,放到缓存中。

分析populateBean:

【AbstractAutowireCapableBeanFactory类】

	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		...
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					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;
				}
			}
		}
		...
}

【AutowiredAnnotationBeanPostProcessor类】
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
	   // 在applyMergedBeanDefinitionPostProcessors中已经将封装好的InjectionMetadata 
	     放到了缓存里,这里就直接从缓存里取值
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
		try {
		   // 开始注入
			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;
	}

【InjectionMetadata】类:
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
        // 这个checkedElements就是在postProcessMergedBeanDefinition中进行赋值的
		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);
			}
		}
	}

【AutowiredAnnotationBeanPostProcessor】类
		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 {
			  // 根据field封装成DependencyDescriptor
				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 {
				//  根据DependencyDescriptor中getDependencyType的class类型去beanFactory获取实例
					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) {
							this.cachedFieldValue = desc;
							registerDependentBeans(beanName, autowiredBeanNames);
							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);
			}
		}
	}

populateBean方法:
1.回调到AutowiredAnnotationBeanPostProcessor中的postProcessProperties方法
2.获取之前定义的InjectionMetadata对象,获取到里面封装的InjectedElement
3.从工厂获取到InjectedElement里需要注入的实例对象
3.利用反射对字段进行赋值

总结:
1. @Autowired什么时候注入?
项目启动后调用容器的refresh()方法,当运行完finishBeanFactoryInitialization()后完成的注入。
2. @Autowired怎么注入?
从容器中获取到需要注入的实例,使用反射完成的注入
3.运行流程?
循环注册每个bean的时候,会看这个bean是否有需要依赖注入的属性,如果有则从容器中获取到需要注入的属性,然后通过反射进行赋值。

你可能感兴趣的:(Spring-IOC)