publicstatic String[] beanNamesForTypeIncludingAncestors(
ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
// 从本容器中找
String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
// 从父容器找并放入resultif (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactoryhbf= (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
// 递归调用
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
// 把从子父Bean工厂找到的值合并去重(有重复用子类的)
result = mergeNamesWithParent(result, parentResult, hbf);
}
}
// 返回找到的所有BeanNamereturn result;
}
/**
* 真正的根据类型获取BeanName的外部方法
*/public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
// 如果没有冻结,就根据类型去BeanFactory找,如果冻结了,可能就跳过这个if然后去缓存中去拿了if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
}
// 把当前类型所匹配的beanName缓存起来
Map<Class<?>, String[]> cache =
(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
// 得到缓冲中的BeanName值
String[] resolvedBeanNames = cache.get(type);
// 得到的值不为null,直接返回if (resolvedBeanNames != null) {
return resolvedBeanNames;
}
// 值为null,重新去获取值
resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true);
// 进行缓存if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) {
cache.put(type, resolvedBeanNames);
}
// 返回所有的BeanNamereturn resolvedBeanNames;
}
/**
* 真正的根据类型获取BeanName的内部方法
*/private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
List<String> result = newArrayList<>();
// Check all bean definitions.// 遍历所有的BeanDefinitionsfor (String beanName : this.beanDefinitionNames) {
// Only consider bean as eligible if the bean name is not defined as alias for some other bean.// 跳过别名if (!isAlias(beanName)) {
try {
// 得到当前Bean合并后的BeanDefinitionRootBeanDefinitionmbd= getMergedLocalBeanDefinition(beanName);
// Only check bean definition if it is complete.// 判断mbd允不允许获取对应类型// 首先mdb不能是抽象的,然后allowEagerInit为true,则直接去推测mdb的类型,并进行匹配// 如果allowEagerInit为false,那就继续判断,如果mdb还没有加载类并且是懒加载的并且不允许提前加载类,那mbd不能用来进行匹配(因为不允许提前加载类,只能在此mdb自己去创建bean对象时才能去创建类)// 如果allowEagerInit为false,并且mbd已经加载类了,或者是非懒加载的,或者允许提前加载类,并且不用必须提前初始化才能获取类型,那么就可以去进行匹配了// 这个条件有点复杂,但是如果只考虑大部分流程,则可以忽略这个判断,因为allowEagerInit传进来的基本上都是trueif (!mbd.isAbstract() && (allowEagerInit ||
(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
!requiresEagerInitForType(mbd.getFactoryBeanName()))) {
// 得到是否是FactoryBeanbooleanisFactoryBean= isFactoryBean(beanName, mbd);
// 得到BeanDefinitionHolderBeanDefinitionHolderdbd= mbd.getDecoratedDefinition();
// 匹配标志falsebooleanmatchFound=false;
// 容许FactoryBean初始化booleanallowFactoryBeanInit= (allowEagerInit || containsSingleton(beanName));
// 是否非懒加载booleanisNonLazyDecorated= (dbd != null && !mbd.isLazyInit());
// 当前BeanDefinition不是FactoryBean,就是普通Beanif (!isFactoryBean) {
// 在筛选Bean时,如果仅仅只包括单例,但是beanName对应的又不是单例,则忽略if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
// 判断类型是否匹配
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
else {
if (includeNonSingletons || isNonLazyDecorated ||
(allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
// 类型匹配-懒加载
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
if (!matchFound) {
// In case of FactoryBean, try to match FactoryBean instance itself next.
beanName = FACTORY_BEAN_PREFIX + beanName;
// 类型匹配-FactoryBean
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
if (matchFound) {
// 将匹配到的,添加到结果集
result.add(beanName);
}
}
}
catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) {
if (allowEagerInit) {
throw ex;
}
// Probably a placeholder: let's ignore it for type matching purposes.LogMessagemessage= (ex instanceof CannotLoadBeanClassException ?
LogMessage.format("Ignoring bean class loading failure for bean '%s'", beanName) :
LogMessage.format("Ignoring unresolvable metadata in bean definition '%s'", beanName));
logger.trace(message, ex);
// Register exception, in case the bean was accidentally unresolvable.
onSuppressedException(ex);
}
catch (NoSuchBeanDefinitionException ex) {
// Bean definition got removed while we were iterating -> ignore.
}
}
}
// Check manually registered singletons too.// 这里的逻辑是在手动注册的bean中看是否有满足条件的for (String beanName : this.manualSingletonNames) {
try {
// In case of FactoryBean, match object created by FactoryBean.if (isFactoryBean(beanName)) {
if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
result.add(beanName);
// Match found for this bean: do not match FactoryBean itself anymore.continue;
}
// In case of FactoryBean, try to match FactoryBean itself next.
beanName = FACTORY_BEAN_PREFIX + beanName;
}
// Match raw bean instance (might be raw FactoryBean).if (isTypeMatch(beanName, type)) {
result.add(beanName);
}
}
catch (NoSuchBeanDefinitionException ex) {
// Shouldn't happen - probably a result of circular reference resolution...
logger.trace(LogMessage.format(
"Failed to check manually registered singleton with name '%s'", beanName), ex);
}
}
// 返回结果数组return StringUtils.toStringArray(result);
}
判断类型是否匹配
protectedbooleanisTypeMatch(String name, ResolvableType typeToMatch, boolean allowFactoryBeanInit)throws NoSuchBeanDefinitionException {
// 判断name所对应的Bean的类型是不是typeToMatch// allowFactoryBeanInit表示允不允许在这里实例化FactoryBean对象// 如果name是&xxx,那么beanName就是xxxStringbeanName= transformedBeanName(name);
// name是不是&xxx(FactoryBean)booleanisFactoryDereference= BeanFactoryUtils.isFactoryDereference(name);
// Check manually registered singletons.// 获取danliBeanObjectbeanInstance= getSingleton(beanName, false);
// 获取到了单例Bean,并且不是空的Beanif (beanInstance != null && beanInstance.getClass() != NullBean.class) {
// FactoryBean的特殊逻辑if (beanInstance instanceof FactoryBean) {
// FactoryBean的外部的类if (!isFactoryDereference) {
// 调用factoryBean.getObjectType()
Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
// 返回当前类型不为空并且类型是否匹配return (type != null && typeToMatch.isAssignableFrom(type));
}
else {
// 返回类型是否匹配return typeToMatch.isInstance(beanInstance);
}
}
// 不是FactoryBean,就是普通Beanelseif (!isFactoryDereference) {
// 直接匹配到,返回true。其实常用的方法,看到这一行就可以了if (typeToMatch.isInstance(beanInstance)) {
// Direct match for exposed instance?returntrue;
}
// 泛型相关的处理elseif (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) {
// Generics potentially only match on the target class, not on the proxy...RootBeanDefinitionmbd= getMergedLocalBeanDefinition(beanName);
Class<?> targetType = mbd.getTargetType();
if (targetType != null && targetType != ClassUtils.getUserClass(beanInstance)) {
// Check raw class match as well, making sure it's exposed on the proxy.
Class<?> classToMatch = typeToMatch.resolve();
if (classToMatch != null && !classToMatch.isInstance(beanInstance)) {
returnfalse;
}
if (typeToMatch.isAssignableFrom(targetType)) {
returntrue;
}
}
ResolvableTyperesolvableType= mbd.targetType;
if (resolvableType == null) {
resolvableType = mbd.factoryMethodReturnType;
}
return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType));
}
}
returnfalse;
}
// 单例池有,但是没有BeanDefinitionMap中没有,返回false。注册了个空实例elseif (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
// null instance registeredreturnfalse;
}
// No singleton instance found -> check bean definition.BeanFactoryparentBeanFactory= getParentBeanFactory();
// 存在父工厂,调用父工厂的isTypeMatch方法if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
}
// 单例池中没有name对应的Bean对象,就只能根据BeanDefinition来判断出类型了// Retrieve corresponding bean definition.RootBeanDefinitionmbd= getMergedLocalBeanDefinition(beanName);
BeanDefinitionHolderdbd= mbd.getDecoratedDefinition();
// Setup the types that we want to match against
Class<?> classToMatch = typeToMatch.resolve();
if (classToMatch == null) {
classToMatch = FactoryBean.class;
}
// 为了判断当前beanName,是不是classToMatch或FactoryBean
Class<?>[] typesToMatch = (FactoryBean.class == classToMatch ?
newClass<?>[] {classToMatch} : newClass<?>[] {FactoryBean.class, classToMatch});
// Attempt to predict the bean type
Class<?> predictedType = null;
// We're looking for a regular reference but we're a factory bean that has// a decorated bean definition. The target bean should be the same type// as FactoryBean would ultimately return. 啃if (!isFactoryDereference && dbd != null && isFactoryBean(beanName, mbd)) {
// We should only attempt if the user explicitly set lazy-init to true// and we know the merged bean definition is for a factory bean.if (!mbd.isLazyInit() || allowFactoryBeanInit) {
RootBeanDefinitiontbd= getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
// getObjectType所方法的类型
Class<?> targetType = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
if (targetType != null && !FactoryBean.class.isAssignableFrom(targetType)) {
predictedType = targetType;
}
}
}
// If we couldn't use the target type, try regular prediction.if (predictedType == null) {
predictedType = predictBeanType(beanName, mbd, typesToMatch);
if (predictedType == null) {
returnfalse;
}
}
// Attempt to get the actual ResolvableType for the bean.ResolvableTypebeanType=null;
// If it's a FactoryBean, we want to look at what it creates, not the factory class.// BeanDefinition的类型是不是FactoryBean,如果是得先实例化FactoryBean这个对象,然后调用getObjectType方法才能知道具体的类型,前提是allowFactoryBeanInit为trueif (FactoryBean.class.isAssignableFrom(predictedType)) {
if (beanInstance == null && !isFactoryDereference) {
beanType = getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit);
predictedType = beanType.resolve();
if (predictedType == null) {
returnfalse;
}
}
}
elseif (isFactoryDereference) {
// Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean// type but we nevertheless are being asked to dereference a FactoryBean...// Let's check the original bean class and proceed with it if it is a FactoryBean.
predictedType = predictBeanType(beanName, mbd, FactoryBean.class);
if (predictedType == null || !FactoryBean.class.isAssignableFrom(predictedType)) {
returnfalse;
}
}
// We don't have an exact type but if bean definition target type or the factory// method return type matches the predicted type then we can use that.if (beanType == null) {
ResolvableTypedefinedType= mbd.targetType;
if (definedType == null) {
definedType = mbd.factoryMethodReturnType;
}
if (definedType != null && definedType.resolve() == predictedType) {
beanType = definedType;
}
}
// If we have a bean type use it so that generics are consideredif (beanType != null) {
return typeToMatch.isAssignableFrom(beanType);
}
// If we don't have a bean type, fallback to the predicted typereturn typeToMatch.isAssignableFrom(predictedType);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)