26、Spring5.x源码之旅二十六getBean详解十一applyMergedBeanDefinitionPostProcessors一

  • 处理器修改合并bean定义
  • CommonAnnotationBeanPostProcessor的postProcessMergedBeanDefinition处理
    • InitDestroyAnnotationBeanPostProcessor的处理
    • findLifecycleMetadata寻找生命周期元数据
    • buildLifecycleMetadata构建生命周期元数据
      • emptyLifecycleMetadata都是空方法
      • LifecycleMetadata的checkConfigMembers
  • findResourceMetadata的处理
    • buildResourceMetadata构建Resource元数据
    • InjectionMetadata的checkConfigMembers

处理器修改合并bean定义

前面实例化完成了,之后要进行处理器的处理,也就是MergedBeanDefinitionPostProcessor处理器的处理:

	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
   
     
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
   
     
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
   
     
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}

CommonAnnotationBeanPostProcessor的postProcessMergedBeanDefinition处理

@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
   
     
		super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
		InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}

InitDestroyAnnotationBeanPostProcessor的处理

这个主要是生命周期的一些回调函数的注册,比如PostConstructPreDestroy注解的方法。

	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
   
     
		LifecycleMetadata metadata = findLifecycleMetadata(beanType);//找到生命周期方法
		metadata.checkConfigMembers(beanDefinition);//注册初始化和销毁的回调方法
	}

findLifecycleMetadata寻找生命周期元数据

private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
   
     
		if (this.lifecycleMetadataCache == null) {
   
     
			// Happens after deserialization, during destruction...
			return buildLifecycleMetadata(clazz);
		}
		// Quick check on the concurrent map first, with minimal locking.//双重检测,尽可能少的用锁
		LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
		if (metadata == null) {
   
     
			synchronized (this.lifecycleMetadataCache) {
   
     
				metadata = this.lifecycleMetadataCache.get(clazz);
				if (metadata == null) {
   
     
					metadata = buildLifecycleMetadata(clazz);
					this.lifecycleMetadataCache.put(clazz, metadata);//放入缓存
				}
				return metadata;
			}
		}
		return metadata;
	}

buildLifecycleMetadata构建生命周期元数据

一般来说都是要经过这步的,因为都需要经过注册,除非是第二次来,有缓存了。
其实就是检测clazz以及父类的所有的方法,看是不是有PostConstructPreDestroy注解,有的话就把方法封装成LifecycleElement加入对应的集合:

private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
   
     
		if (!AnnotationUtils.isCandidateClass(clazz, Arrays.asList(this.initAnnotationType, this.destroyAnnotationType))) {
   
     
			return this.emptyLifecycleMetadata;
		}

		List<LifecycleElement> initMethods = new ArrayList<>();
		List<LifecycleElement> destroyMethods = new ArrayList<>();
		Class<?> targetClass = clazz;

		do {
   
     
			final List<LifecycleElement> currInitMethods = new ArrayList<>();
			final List<LifecycleElement> currDestroyMethods = new ArrayList<>();
			//如果有PostConstruct和PreDestroy注解的方法就添加到currInitMethods和currDestroyMethods里,包括父类,因为可能CGLIB动态代理
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
   
     
				if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
   
     
					LifecycleElement element = new LifecycleElement(method);
					currInitMethods.add(element);
					if (logger.isTraceEnabled()) {
   
     
						logger.trace("Found init method on class [" + clazz.getName() + "]: " + method);
					}
				}
				if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
   
     
					currDestroyMethods.add(new LifecycleElement(method));
					if (logger.isTraceEnabled()) {
   
     
						logger.trace("Found destroy method on class [" + clazz.getName() + "]: " + method);
					}
				}
			});
			//加入相应的声明周期方法里
			initMethods.addAll(0, currInitMethods);
			destroyMethods.addAll(currDestroyMethods);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);
		//有一个不为空就封装一个LifecycleMetadata返回,否则就返回空的emptyLifecycleMetadata
		return (initMethods.isEmpty() && destroyMethods.isEmpty() ? this.emptyLifecycleMetadata :
				new LifecycleMetadata(clazz, initMethods, destroyMethods));
	}

emptyLifecycleMetadata都是空方法

如果没有注解的话会返回一个空的emptyLifecycleMetadata

private final transient LifecycleMetadata emptyLifecycleMetadata =
			new LifecycleMetadata(Object.class, Collections.emptyList(), Collections.emptyList()) {
   
     
				@Override
				public void checkConfigMembers(RootBeanDefinition beanDefinition) {
   
     
				}
				@Override
				public void invokeInitMethods(Object target, String beanName) {
   
     
				}
				@Override
				public void invokeDestroyMethods(Object target, String beanName) {
   
     
				}
				@Override
				public boolean hasDestroyMethods() {
   
     
					return false;
				}
			};
LifecycleMetadata的checkConfigMembers

会将初始化和销毁的回调方法注册到beanDefinition中,并且标记已经检查过的方法,放入checkedInitMethodscheckedDestroyMethods 方法集合。

public void checkConfigMembers(RootBeanDefinition beanDefinition) {
   
     
			Set<LifecycleElement> checkedInitMethods = new LinkedHashSet<>(this.initMethods.size());
			for (LifecycleElement element : this.initMethods) {
   
     
				String methodIdentifier = element.getIdentifier();
				if (!beanDefinition.isExternallyManagedInitMethod(methodIdentifier)) {
   
     
					beanDefinition.registerExternallyManagedInitMethod(methodIdentifier);//注册初始化调用方法
					checkedInitMethods.add(element);
					if (logger.isTraceEnabled()) {
   
     
						logger.trace("Registered init method on class [" + this.targetClass.getName() + "]: " + element);
					}
				}
			}
			Set<LifecycleElement> checkedDestroyMethods = new LinkedHashSet<>(this.destroyMethods.size());
			for (LifecycleElement element : this.destroyMethods) {
   
     
				String methodIdentifier = element.getIdentifier();
				if (!beanDefinition.isExternallyManagedDestroyMethod(methodIdentifier)) {
   
     
					beanDefinition.registerExternallyManagedDestroyMethod(methodIdentifier);//注册销毁调用方法
					checkedDestroyMethods.add(element);
					if (logger.isTraceEnabled()) {
   
     
						logger.trace("Registered destroy method on class [" + this.targetClass.getName() + "]: " + element);
					}
				}
			}
			this.checkedInitMethods = checkedInitMethods;
			this.checkedDestroyMethods = checkedDestroyMethods;
		}

findResourceMetadata的处理

跟上面一样的结构,主要是解析Resource注解啦。

private InjectionMetadata findResourceMetadata(String beanName, final 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);
					}
					metadata = buildResourceMetadata(clazz);//创建Resource注解注入元数据
					this.injectionMetadataCache.put(cacheKey, metadata);
				}
			}
		}
		return metadata;
	}

buildResourceMetadata构建Resource元数据

别看好像那么长,其实跟前面差不多,这次是会看是否有webService,ejb,Resource的属性注解和方法注解,有的话也封装成注入元数据InjectionMetadata返回。

private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {
   
     
		if (!AnnotationUtils.isCandidateClass(clazz, resourceAnnotationTypes)) {
   
     
			return InjectionMetadata.EMPTY;
		}

		List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
		Class<?> targetClass = clazz;

		do {
   
     
			final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
			//查询是否有webService,ejb,Resource的属性注解,但是不支持静态属性
			ReflectionUtils.doWithLocalFields(targetClass, field -> {
   
     
				if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) {
   
     
					if (Modifier.isStatic(field.getModifiers())) {
   
     
						throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields");
					}
					currElements.add(new WebServiceRefElement(field, field, null));
				}
				else if (ejbRefClass != null && field.isAnnotationPresent(ejbRefClass)) {
   
     
					if (Modifier.isStatic(field.getModifiers())) {
   
     
						throw new IllegalStateException("@EJB annotation is not supported on static fields");
					}
					currElements.add(new EjbRefElement(field, field, null));
				}
				else if (field.isAnnotationPresent(Resource.class)) {
   
     
					if (Modifier.isStatic(field.getModifiers())) {
   
     
						throw new IllegalStateException("@Resource annotation is not supported on static fields");
					}
					if (!this.ignoredResourceTypes.contains(field.getType().getName())) {
   
     
						currElements.add(new ResourceElement(field, field, null));
					}
				}
			});
			//处理方法,桥接方法可以理解为解决老版本的类型转换问题,这里你就理解成就是普通方法
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
   
     
				Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
				if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
   
     
					return;
				}
				if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
   
     
					if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) {
   
     
						if (Modifier.isStatic(method.getModifiers())) {
   
     
							throw new IllegalStateException("@WebServiceRef annotation is not supported on static methods");
						}
						if (method.getParameterCount() != 1) {
   
     
							throw new IllegalStateException("@WebServiceRef annotation requires a single-arg method: " + method);
						}
						PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
						currElements.add(new WebServiceRefElement(method, bridgedMethod, pd));
					}
					else if (ejbRefClass != null && bridgedMethod.isAnnotationPresent(ejbRefClass)) {
   
     
						if (Modifier.isStatic(method.getModifiers())) {
   
     
							throw new IllegalStateException("@EJB annotation is not supported on static methods");
						}
						if (method.getParameterCount() != 1) {
   
     
							throw new IllegalStateException("@EJB annotation requires a single-arg method: " + method);
						}
						PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
						currElements.add(new EjbRefElement(method, bridgedMethod, pd));
					}
					else if (bridgedMethod.isAnnotationPresent(Resource.class)) {
   
     
						if (Modifier.isStatic(method.getModifiers())) {
   
     //静态不行
							throw new IllegalStateException("@Resource annotation is not supported on static methods");
						}
						Class<?>[] paramTypes = method.getParameterTypes();
						if (paramTypes.length != 1) {
   
     //需要有一个参数
							throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method);
						}
						if (!this.ignoredResourceTypes.contains(paramTypes[0].getName())) {
   
     
							PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
							currElements.add(new ResourceElement(method, bridgedMethod, pd));
						}
					}
				}
			});

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

		return InjectionMetadata.forElements(elements, clazz);
	}

InjectionMetadata的checkConfigMembers

这个也是一样,把元素注册进beanDefinition里。

public void checkConfigMembers(RootBeanDefinition beanDefinition) {
   
     
		Set<InjectedElement> checkedElements = new LinkedHashSet<>(this.injectedElements.size());
		for (InjectedElement element : this.injectedElements) {
   
     
			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;
	}

CommonAnnotationBeanPostProcessor就那么多了,其他的后面写吧。

好了,今天就到这里了,希望对学习理解有帮助,大神看见勿喷,仅为自己的学习理解,能力有限,请多包涵。