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<>();