请选择 进入手机版 | 继续访问电脑版
MSIPO技术圈 首页 IT技术 查看内容

一起学SF框架系列5.7-模块Beans-BeanDefinition使用

2023-07-13

SF如何使用BeanDefinition达成其目标IoC,我们通过跟踪BeanDefinition使用来了解。

使用起点

跟踪SF初始化过程,第一个点在:DefaultListableBeanFactory.preInstantiateSingletons。如下图:
在这里插入图片描述
RootBeanDefinition是运行时Spring BeanFactory使用的bean定义,可能是由多个相互继承的原始BeanDefinition(从配置元数据中解析生成的)合并创建而来。本质上可RootBeanDefinition当做运行时的“统一”bean定义视图。
注:此处生成bd(RootBeanDefinition)并没有传入到方法getBean(beanName),是因为第一次生成后就缓存在beanFactory,下次直接从缓存获得即可。

类-RootBeanDefinition

RootBeanDefinition继承于AbstractBeanDefinition,主要增强或限制:
1、不能有继承(都被合并):setParentName总是null;
2、确定bean解析器,包括注解、反射类型、class、工厂方法和supplier;
3、管理外部管理器:Member、初始化方法和销毁方法等;

@SuppressWarnings("serial")
public class RootBeanDefinition extends AbstractBeanDefinition {
	//省略属性及11种构建函数

	/* ParentName操作:ParentName必须为空(所有的继承类都合并成一个bean,这是RootBeanDefinition 的本质) */
	@Override
	public String getParentName() {
		return null;
	}
	@Override
	public void setParentName(@Nullable String parentName) {
		if (parentName != null) {
			throw new IllegalArgumentException("Root bean cannot be changed into a child bean with parent reference");
		}
	}

	/* BeanDefinitionHolder(bean id、alias与BeanDefinition对应关系)操作*/
	public void setDecoratedDefinition(@Nullable BeanDefinitionHolder decoratedDefinition) {
		this.decoratedDefinition = decoratedDefinition;
	}
	@Nullable
	public BeanDefinitionHolder getDecoratedDefinition() {
		return this.decoratedDefinition;
	}

	/* bean的注解元素(含bean的所有注解)操作 */
	public void setQualifiedElement(@Nullable AnnotatedElement qualifiedElement) {
		this.qualifiedElement = qualifiedElement;
	}
	@Nullable
	public AnnotatedElement getQualifiedElement() {
		return this.qualifiedElement;
	}

	/** bean对应的解析类操作 
	解析类可以是ResolvableType 或者Class
	ResolvableType:是Java.lang.reflect.Type的封装,最终将beanDefinition解析到对应Class的能力
	Class:bean直接对应的Class
	*/
	public void setTargetType(@Nullable ResolvableType targetType) {
		this.targetType = targetType;
	}
	public void setTargetType(@Nullable Class<?> targetType) {
		this.targetType = (targetType != null ? ResolvableType.forClass(targetType) : null);
	}
	@Nullable
	public Class<?> getTargetType() {
		if (this.resolvedTargetType != null) {
			return this.resolvedTargetType;
		}
		ResolvableType targetType = this.targetType;
		return (targetType != null ? targetType.resolve() : null);
	}
	@Override
	public ResolvableType getResolvableType() {
		ResolvableType targetType = this.targetType;
		if (targetType != null) {
			return targetType;
		}
		ResolvableType returnType = this.factoryMethodReturnType;
		if (returnType != null) {
			return returnType;
		}
		Method factoryMethod = this.factoryMethodToIntrospect;
		if (factoryMethod != null) {
			return ResolvableType.forMethodReturnType(factoryMethod);
		}
		return super.getResolvableType();
	}

	/* 获得用于默认构造的首选构造函数(可以是多个)。如有必要,构造函数参数可以自动注入 */
	@Nullable
	public Constructor<?>[] getPreferredConstructors() {
		return null;
	}

	/* 设置非重载方法工厂方法名称*/
	public void setUniqueFactoryMethodName(String name) {
		Assert.hasText(name, "Factory method name must not be empty");
		setFactoryMethodName(name);
		this.isFactoryMethodUnique = true;
	}
	/* 设置重载方法工厂方法名称 */
	public void setNonUniqueFactoryMethodName(String name) {
		Assert.hasText(name, "Factory method name must not be empty");
		setFactoryMethodName(name);
		this.isFactoryMethodUnique = false;
	}
	/* 判定是否是工厂方法 */
	public boolean isFactoryMethod(Method candidate) {
		return candidate.getName().equals(getFactoryMethodName());
	}
	/* 设置工厂方法的解析方法器(Java Method)  */
	public void setResolvedFactoryMethod(@Nullable Method method) {
		this.factoryMethodToIntrospect = method;
		if (method != null) {
			setUniqueFactoryMethodName(method.getName());
		}
	}
	/* 获取工厂方法的解析方法器(Java Method)  */
	@Nullable
	public Method getResolvedFactoryMethod() {
		return this.factoryMethodToIntrospect;
	}

	/* 设置bean的实例生产者 */
	@Override
	public void setInstanceSupplier(@Nullable Supplier<?> supplier) {
		super.setInstanceSupplier(supplier);
		Method factoryMethod = (supplier instanceof InstanceSupplier<?> instanceSupplier ?
				instanceSupplier.getFactoryMethod() : null);
		if (factoryMethod != null) {
			setResolvedFactoryMethod(factoryMethod);
		}
	}

	// 标识BeanDefinition是否已被MergedBeanDefinitionPostProcessor处理过
	public void markAsPostProcessed() {
		synchronized (this.postProcessingLock) {
			this.postProcessed = true;
		}
	}

	// 注册外部管理的Member(Member代表a field or a method or a constructor)
	public void registerExternallyManagedConfigMember(Member configMember) {
		synchronized (this.postProcessingLock) {
			if (this.externallyManagedConfigMembers == null) {
				this.externallyManagedConfigMembers = new LinkedHashSet<>(1);
			}
			this.externallyManagedConfigMembers.add(configMember);
		}
	}
	// 判断是否外部管理Member
	public boolean isExternallyManagedConfigMember(Member configMember) {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedConfigMembers != null &&
					this.externallyManagedConfigMembers.contains(configMember));
		}
	}
	// 获得外部管理Set<Member>
	public Set<Member> getExternallyManagedConfigMembers() {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedConfigMembers != null ?
					Collections.unmodifiableSet(new LinkedHashSet<>(this.externallyManagedConfigMembers)) :
					Collections.emptySet());
		}
	}

	// 注册外部管理的初始化方法(例如,用JSR-250的注解是用jakarta.annotation.PostConstruct初始化)
	public void registerExternallyManagedInitMethod(String initMethod) {
		synchronized (this.postProcessingLock) {
			if (this.externallyManagedInitMethods == null) {
				this.externallyManagedInitMethods = new LinkedHashSet<>(1);
			}
			this.externallyManagedInitMethods.add(initMethod);
		}
	}
	// 判断是否是外部管理的初始化方法
	public boolean isExternallyManagedInitMethod(String initMethod) {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedInitMethods != null &&
					this.externallyManagedInitMethods.contains(initMethod));
		}
	}
	// 判断是否是外部管理的初始化方法(忽略方法的可见性)
	boolean hasAnyExternallyManagedInitMethod(String initMethod) {
		synchronized (this.postProcessingLock) {
			if (isExternallyManagedInitMethod(initMethod)) {
				return true;
			}
			if (this.externallyManagedInitMethods != null) {
				for (String candidate : this.externallyManagedInitMethods) {
					int indexOfDot = candidate.lastIndexOf('.');
					if (indexOfDot >= 0) {
						String methodName = candidate.substring(indexOfDot + 1);
						if (methodName.equals(initMethod)) {
							return true;
						}
					}
				}
			}
			return false;
		}
	}
	// 获得外部管理的初始化方法
	public Set<String> getExternallyManagedInitMethods() {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedInitMethods != null ?
					Collections.unmodifiableSet(new LinkedHashSet<>(this.externallyManagedInitMethods)) :
					Collections.emptySet());
		}
	}

	// 解析可推测的bean销毁方法
	public void resolveDestroyMethodIfNecessary() {
		setDestroyMethodNames(DisposableBeanAdapter
				.inferDestroyMethodsIfNecessary(getResolvableType().toClass(), this));
	}
	// 注册外部管理的销毁方法
	public void registerExternallyManagedDestroyMethod(String destroyMethod) {
		synchronized (this.postProcessingLock) {
			if (this.externallyManagedDestroyMethods == null) {
				this.externallyManagedDestroyMethods = new LinkedHashSet<>(1);
			}
			this.externallyManagedDestroyMethods.add(destroyMethod);
		}
	}
	// 判断是否是外部管理的销毁方法
	public boolean isExternallyManagedDestroyMethod(String destroyMethod) {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedDestroyMethods != null &&
					this.externallyManagedDestroyMethods.contains(destroyMethod));
		}
	}
	// 判断是否是外部管理的销毁方法(忽略方法的可见性)
	boolean hasAnyExternallyManagedDestroyMethod(String destroyMethod) {
		synchronized (this.postProcessingLock) {
			if (isExternallyManagedDestroyMethod(destroyMethod)) {
				return true;
			}
			if (this.externallyManagedDestroyMethods != null) {
				for (String candidate : this.externallyManagedDestroyMethods) {
					int indexOfDot = candidate.lastIndexOf('.');
					if (indexOfDot >= 0) {
						String methodName = candidate.substring(indexOfDot + 1);
						if (methodName.equals(destroyMethod)) {
							return true;
						}
					}
				}
			}
			return false;
		}
	}
	// 获得外部管理的销毁方法
	public Set<String> getExternallyManagedDestroyMethods() {
		synchronized (this.postProcessingLock) {
			return (this.externallyManagedDestroyMethods != null ?
					Collections.unmodifiableSet(new LinkedHashSet<>(this.externallyManagedDestroyMethods)) :
					Collections.emptySet());
		}
	}

	//克隆一个新的RootBeanDefinition 
	@Override
	public RootBeanDefinition cloneBeanDefinition() {
		return new RootBeanDefinition(this);
	}

	//类相等判断
	@Override
	public boolean equals(@Nullable Object other) {
		return (this == other || (other instanceof RootBeanDefinition && super.equals(other)));
	}

	//类串化判断
	@Override
	public String toString() {
		return "Root bean: " + super.toString();
	}
}

方法-getMergedLocalBeanDefinition(String beanName)

	protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
		// 从缓存获取
		RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
		if (mbd != null && !mbd.stale) {
			return mbd;
		}
		// 新建RootBeanDefinition 
		return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
	}

	/* 过渡类 */
	protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
			throws BeanDefinitionStoreException {

		return getMergedBeanDefinition(beanName, bd, null);
	}

	/** 真正实现合并BeanDefinition(主要合并继承关系) 
	 * @param beanName:要合并的beanName
	 * @param bd:bean定义解析生成的BeanDefinition
	 * @param containingBd:对于内部类情况,包容该bean的BeanDefinition
	*/
	protected RootBeanDefinition getMergedBeanDefinition(
			String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
			throws BeanDefinitionStoreException {
		//同步执行
		synchronized (this.mergedBeanDefinitions) {
			RootBeanDefinition mbd = null;
			RootBeanDefinition previous = null;

			// 不是内部类bean,从缓存获取一次(两次检测)
			if (containingBd == null) {
				mbd = this.mergedBeanDefinitions.get(beanName);
			}

			/* 合并处理 mbd.stale-需要合并标志 */
			if (mbd == null || mbd.stale) {
				// 处理前的mbd
				previous = mbd;
				if (bd.getParentName() == null) {
				// bd没有父级
					// Use copy of given root bean definition.
					if (bd instanceof RootBeanDefinition rootBeanDef) {
						// 如果bd已经是RootBeanDefinition,直接克隆一份
						mbd = rootBeanDef.cloneBeanDefinition();
					}
					else {
						// 用bd生成RootBeanDefinition
						mbd = new RootBeanDefinition(bd);
					}
				}
				else {
				// bd还有父级
					// Child bean definition: needs to be merged with parent.
					BeanDefinition pbd;
					try {
						String parentBeanName = transformedBeanName(bd.getParentName());
						if (!beanName.equals(parentBeanName)) {
							// 有真正的父级bean,合并方式生成父级BeanDefinition (此处是递归调用,因此可以合并所有继承关系)
							pbd = getMergedBeanDefinition(parentBeanName);
						}
						else {
							// 父级beanName同本身beanName相同,可能来自父级BeanFactory,从父级BeanFactory合并方式生成BeanDefinition 
							if (getParentBeanFactory() instanceof ConfigurableBeanFactory parent) {
								pbd = parent.getMergedBeanDefinition(parentBeanName);
							}
							else {
								throw new NoSuchBeanDefinitionException(parentBeanName,
										"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
												"': cannot be resolved without a ConfigurableBeanFactory parent");
							}
						}
					}
					catch (NoSuchBeanDefinitionException ex) {
						throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
								"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
					}
					// 以父级bean生成新RootBeanDefinition,然后用孩子bd的重写(子类有的就覆盖父类),这样就把父子合并了(因为是递归调用,因此可以合并所有继承关系)
					mbd = new RootBeanDefinition(pbd);
					mbd.overrideFrom(bd);
				}

				// Set default singleton scope, if not configured before.
				if (!StringUtils.hasLength(mbd.getScope())) {
					mbd.setScope(SCOPE_SINGLETON);
				}

				// 如果是内部类,scope同包容bean的scope
				if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
					mbd.setScope(containingBd.getScope());
				}

				// 非内部类进行缓存 (isCacheBeanMetadata()代表来自缓存的元数据)
				if (containingBd == null && isCacheBeanMetadata()) {
					this.mergedBeanDefinitions.put(beanName, mbd);
				}
			}
			if 

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部