spring启动流程探索四、refresh()(3)getBeanNamesForType-isTypeMatch

本文主要探讨Spring框架中getBeanNamesForType方法的内部逻辑,该方法遍历bean定义并使用isTypeMatch判断类型匹配。isTypeMatch方法包括判断单例、检查bean定义、预测bean类型以及获取实际类型的过程,用于确定bean是否符合给定的类型。文章简述了关键步骤,并提出可能遗漏的细节可另开章节深入讨论。
摘要由CSDN通过智能技术生成

getBeanNamesForType

这个方法其实讲起来还挺复杂的,因为他里面调用很多的其他方法,而那些其他的方法内容也很繁琐,所以我先大家定个主题,我们在这只探讨和上个章节展开一致的内容,是沿着我们refresh的流程往下走的,所以如果大家在看的时候要明确。上代码:

beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
@Override
	public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
   
		// 跟着调用链过来,就可以发现我们allowEagerInit为false,所以要走的是doGetBeanNamesForType这个方法
		if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
   
			return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
		}
		// 这里是根据是否包含空单例这个标识includeNonSingletons 拿缓存
		Map<Class<?>, String[]> cache =
				(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
		// 如果缓存中有,直接返回
		String[] resolvedBeanNames = cache.get(type);
		if (resolvedBeanNames != null) {
   
			return resolvedBeanNames;
		}
	
		resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true);
		if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) {
   
			cache.put(type, resolvedBeanNames);
		}
		return resolvedBeanNames;
	}

看了这个方法,然后根据我们调用链传进的参数,我们大概就知道要走的方法是

 doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit)

在这里大家要记得一个事情,type是用ResolvableType.forRawClass包装了下

public static ResolvableType forRawClass(@Nullable Class<?> clazz) {
   
		return new ResolvableType(clazz) {
   
			@Override
			public ResolvableType[] getGenerics() {
   
				return EMPTY_TYPES_ARRAY;
			}
			@Override
			public boolean isAssignableFrom(Class<?> other) {
   
				return (clazz == null || ClassUtils.isAssignable(clazz, other));
			}
			@Override
			public boolean isAssignableFrom(ResolvableType other) {
   
				Class<?> otherClass = other.resolve();
				return (otherClass != null && (clazz == null || ClassUtils.isAssignable(clazz, otherClass)));
			}
		};
	}

然后包装的时候重写了三个方法,这重写的三个方法在isTypeMatch方法中将会用到

private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
   
		List<String> result = new ArrayList<>();

		
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值