Spring 5.x 源码之旅-26getBean详解十一applyMergedBeanDefinitionPostProcessors

作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO

联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬

学习必须往深处挖,挖的越深,基础越扎实!

阶段1、深入多线程

阶段2、深入多线程设计模式

阶段3、深入juc源码解析


阶段4、深入jdk其余源码解析


阶段5、深入jvm源码解析

码哥源码部分

码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】

码哥讲源码【炸雷啦!炸雷啦!黄光头他终于跑路啦!】

码哥讲源码-【jvm课程前置知识及c/c++调试环境搭建】

​​​​​​码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】

码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】

码哥讲源码【你水不是你的错,但是你胡说八道就是你不对了!】

码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!

打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】

 

处理器修改合并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中,并且标记已经检查过的方法,放入checkedInitMethods 和checkedDestroyMethods 方法集合。

    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就那么多了,其他的后面写吧。

  • 21
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值