IOC容器启动源码第3、4、5步分析-容器加载了哪些非Bean对象?

继续顺着IoC容器启动源码第1、2步分析-Bean是如何注册进IoC容器的?写下去,从第三步开始分析了:

prepareBeanFactory

// 3. 准备当前上下文要用的BeanFactory
prepareBeanFactory(beanFactory);

这个方法主要是进行beanFactory的一些配置,要了解还是先看一下BeanFactory中有哪些属性,下面是AbstractBeanFactory的部分源码:

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    //父级的BeanFactory,提供bean的继承支持
    @Nullable
    private BeanFactory parentBeanFactory;

    //用于加载bean class 的类加载器
    @Nullable
    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    // 暂时性用于加载bean class 的类加载器
    @Nullable
    private ClassLoader tempClassLoader;

    //是否缓存bean的元信息
    private boolean cacheBeanMetadata = true;

    //用于解析bean定义表达式的解析器
    @Nullable
    private BeanExpressionResolver beanExpressionResolver;

    //数据类型转换器,用于代替PropertyEditors
    @Nullable
    private ConversionService conversionService;

    //自定义注册属性编辑器
    private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4);

    //自定义属性编辑器
    private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4);

    //自定义类型转换器,用于代替PropertyEditor
    @Nullable
    private TypeConverter typeConverter;

    //字符串解析器
    private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>();

    // BeanPostProcessors用于bean的创建前操作
    private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();

    //是否有InstantiationAwareBeanPostProcessor被注册过
    private volatile boolean hasInstantiationAwareBeanPostProcessors;

    //是否有DestructionAwareBeanPostProcessor被注册过
    private volatile boolean hasDestructionAwareBeanPostProcessors;

    //范围(scope)标识->scope的map
    private final Map<String, Scope> scopes = new LinkedHashMap<>(8);

    //运行SecurityManager时启用的安全上下文
    @Nullable
    private SecurityContextProvider securityContextProvider;

    //beanName->RootBeanDefinition的map
    private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);

    //至少创建过一次的bean名称
    private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));

    //正在创建的bean名称
    private final ThreadLocal<Object> prototypesCurrentlyInCreation =
            new NamedThreadLocal<>("Prototype beans currently in creation");
    //...
}
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // 使用上下文类加载器
    beanFactory.setBeanClassLoader(getClassLoader());
    //设置解析bean定义表达式的解析器
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    //添加PropertyEditor注册
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    // 添加一个BeanPostProcessor
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    //忽略以下的这些类作为bean
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

    // 将本身作为依赖注册进容器
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    // 注册 探测事件监听器的 PostProcessor
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // Detect a LoadTimeWeaver and prepare for weaving, if found.
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        // Set a temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }

    // 将一些环境信息注册为bean
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
}

可见这个步骤中配置了一些BeanFactory的属性,并要求忽略一些Bean的注册,又将自己作为依赖注册进了容器,并将一些环境信息注册为bean。下面看一下注册依赖这部分的源码:

@Override
public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) {
    Assert.notNull(dependencyType, "Dependency type must not be null");
    if (autowiredValue != null) {
        if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) {
            throw new IllegalArgumentException("Value [" + autowiredValue +
                    "] does not implement specified dependency type [" + dependencyType.getName() + "]");
        }
        this.resolvableDependencies.put(dependencyType, autowiredValue);
    }
}

注意这里是把依赖类型和要注入的值放入了一个resolvableDependencies中,它是一个ConcurrentHashMap。那么根据上面那个方法的信息,可以知道在加载过程中容器将自身和以下几个依赖类型关联了起来:

  • BeanFactory -> beanFactory
  • ResourceLoader -> this
  • ApplicationEventPublisher -> this
  • ApplicationContext -> this

特别注意的是第一个类型BeanFactory注册的是内部的beanFactory,其他的类型则注册的是本身ApplicationContext 所以如果从容器中按类型进行依赖查找,BeanFactoryApplicationContext找出来的是不一样的对象。

而环境信息则是分别注册了以下几个单例bean:

BeanName 类型 描述
environment ConfigurableEnvironment 外部化配置及Profiles
systemProperties Map<String, Object> JVM系统属性
systemEnvironment Map<String, Object> 系统环境变量

下面是注册单例Bean的实现:

@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
    //注册单例bean
    super.registerSingleton(beanName, singletonObject);
    //在内部的manualSingletonNames添加单例bean名称
    updateManualSingletonNames(set -> set.add(beanName), set -> !this.beanDefinitionMap.containsKey(beanName));
    //清除按类型依赖查找的缓存
    clearByTypeCache();
}

这个super.registerSingleton指的是DefaultSingletonBeanRegistry中的实现,可见DefaultListableBeanFactory组合了许多接口的功能。

public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
    Assert.notNull(beanName, "Bean name must not be null");
    Assert.notNull(singletonObject, "Singleton object must not be null");
    // singletonObjects 就是用于存放单例对象的容器
    synchronized (this.singletonObjects) {
        Object oldObject = this.singletonObjects.get(beanName);
        //如果beanName对应的单例有冲突
        if (oldObject != null) {
            throw new IllegalStateException("Could not register object [" + singletonObject +
                    "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
        }
        //添加进容器
        addSingleton(beanName, singletonObject);
    }
}
protected void addSingleton(String beanName, Object singletonObject) {
    synchronized (this.singletonObjects) {
        //单例对象的缓存,beanName->Object
        this.singletonObjects.put(beanName, singletonObject);
        //单例工厂的缓存,beanName->ObjectFactory
        this.singletonFactories.remove(beanName);
        //提前曝光的单例对象的缓存,beanName->Object
        this.earlySingletonObjects.remove(beanName);
        //注册的单例对象beanName的集合
        this.registeredSingletons.add(beanName);
    }
}

这些容器位于 DefaultSingletonBeanRegistry 的内部。注意singletonObjectssingletonFactoriesearlySingletonObjects其实是形成了三级缓存,后面会分析到。

postProcessBeanFactory

然后看第四步:

// 4. 在子类中允许BeanFactory的Post-processing处理
postProcessBeanFactory(beanFactory);

它是允许子类对BeanFactory的一些前置处理,例如在Web环境会有实现,但在AbstactApplicationContext中为空实现,那就跳过这一步吧。

invokeBeanFactoryPostProcessors

// 5. 调用所有以Bean身份注册的BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    //调用一些BeanFactoryPostProcessors
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

    // 类加载期间的织入,不看
    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
}

先看getBeanFactoryPostProcessors获得的是什么:

public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
    return this.beanFactoryPostProcessors;
}

就是AbstactApplicationContext内部的beanFactoryPostProcessors,类型是List<BeanFactoryPostProcessor>

BeanFactoryPostProcessor是Spring早期的一个接口,它允许用户实现并注册进容器中,可以在bean创建之前,通过BeanFactory修改一些配置。

继续看PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors

public static void invokeBeanFactoryPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

    Set<String> processedBeans = new HashSet<>();

    if (beanFactory instanceof BeanDefinitionRegistry) {
        //转成注册中心接口使用
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                BeanDefinitionRegistryPostProcessor registryProcessor =
                        (BeanDefinitionRegistryPostProcessor) postProcessor;
                //调用BeanDefinitionRegistryPostProcessor预处理BeanDefinitionRegistry
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                registryProcessors.add(registryProcessor);
            }
            else {
                regularPostProcessors.add(postProcessor);
            }
        }


        List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

        // 获取所有注册的BeanDefinitionRegistryPostProcessor
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                //添加到currentRegistryProcessors中
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }

        //对 currentRegistryProcessors 按照优先级排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        // 添加到registryProcessors中
        registryProcessors.addAll(currentRegistryProcessors);
        // 调用这些BeanDefinitionRegistryPostProcessors
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();

        // 获取所有注册的BeanDefinitionRegistryPostProcessor
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        //对 currentRegistryProcessors 按照实现顺序排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        // 调用这些BeanDefinitionRegistryPostProcessors
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();

        // 最终调用所有其他的BeanDefinitionRegistryPostProcessors 
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }

        // 调用所有的BeanFactoryPostProcessor
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }

    // 如果不是BeanDefinitionRegistry,逻辑和上面其实差不多
    else {
        // Invoke factory processors registered with the context instance.
        invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }

    // Do not initialize FactoryBeans here: We need to leave all regular beans
    // uninitialized to let the bean factory post-processors apply to them!
    String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (processedBeans.contains(ppName)) {
            // skip - already processed in first phase above
        }
        else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // Finally, invoke all other BeanFactoryPostProcessors.
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

    // 清除bean definition 元数据缓存
    beanFactory.clearMetadataCache();
}

这个方法其实就是调用了一下注册的beanFactoryPostProcessors和BeanDefinitionRegistryPostProcessor。注意Spring中许多类都会有这样的类似的命名方式(后缀模式,*PostProcessor),代表实现一类功能。

这个方法中有几个方法值得关注:

首先是

beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

这个看名字大概知道是根据Bean的类型查找beanName,可以回想起之前看DefaultListableBeanFactory源码中有一个依赖类型对应BeanName的map,可能和这个有关,看一下实现:

public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
    //上面传过来的allowEagerInit为false,这里会执行
    if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
        return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
    }
    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

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

    //在所有的beanName中检查
    for (String beanName : this.beanDefinitionNames) {
        // 如果不是别名
        if (!isAlias(beanName)) {
            try {
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                //...
}

有一个小插曲,这里有一个RootBeanDefinition类,之前提了一下BeanDefinition接口大致是定义了一些Bean的信息,而其实现类却没有了解,通过查看类图可知其直接实现类大致有三个:

IOC容器启动源码第3、4、5步分析-容器加载了哪些非Bean对象?
  • GenericBeanDefinition:标准bean definition,是通用的实现类。GenericBeanDefinition源码相对AbstractBeanDefinition只增加了一个parentName的属性值,通过该属性构造BeanDefinition的层级关系。
  • ChildBeanDefinition:子Bean定义信息,依赖于其父级BeanDefinition,可以继承其父级BeanDefinition的设置,但现在基本上都已经靠使用GenericBeanDefinition替代ChildBeanDefinition了。
  • RootBeanDefinition:通常指没有父级的BeanDefinition(即最高级),它也表明它是一个可合并的BeanDefinition(可以将RootBeanDefinition的属性合并到子BeanDefinition上)。

那么上面的getMergedLocalBeanDefinition是什么意思呢?其实就是根据beanName获取一个RootBeanDefinition,这个RootBeanDefinition是当bean有父级BeanDefinition的时候,会将父级的属性与其合并,合并后的所有RootBeanDefinition会放在AbstractBeanFactorymergedBeanDefinitions集合中。

protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
    RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
    //如果map中能取到对应的合并后的BeanDefinition,就直接返回
    if (mbd != null && !mbd.stale) {
        return mbd;
    }
    // 否则进行合并
    return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
        throws BeanDefinitionStoreException {

    return getMergedBeanDefinition(beanName, bd, null);
}
protected RootBeanDefinition getMergedBeanDefinition(
        String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
        throws BeanDefinitionStoreException {

    synchronized (this.mergedBeanDefinitions) {
        RootBeanDefinition mbd = null;
        RootBeanDefinition previous = null;

        if (containingBd == null) {
            mbd = this.mergedBeanDefinitions.get(beanName);
        }

        // 是否存在原有的合并后的BeanDefinition,或是否失效
        if (mbd == null || mbd.stale) {
            previous = mbd;
            // 获取父级BeanDefinition的名称,如果为null
            if (bd.getParentName() == null) {
                // 如果该bean本身就是RootBeanDefinition,直接使用复制
                if (bd instanceof RootBeanDefinition) {
                    mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
                }
                // 否则,直接使用该bean创建一个RootBeanDefinition
                else {
                    mbd = new RootBeanDefinition(bd);
                }
            }
            // 如果有父级BeanDefinition
            else {
                BeanDefinition pbd;
                try {
                    String parentBeanName = transformedBeanName(bd.getParentName());
                    if (!beanName.equals(parentBeanName)) {
                        // 递归进行合并
                        pbd = getMergedBeanDefinition(parentBeanName);
                    }
                    else {
                        BeanFactory parent = getParentBeanFactory();
                        if (parent instanceof ConfigurableBeanFactory) {
                            pbd = ((ConfigurableBeanFactory) 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);
                }
                // Deep copy with overridden values.
                mbd = new RootBeanDefinition(pbd);
                mbd.overrideFrom(bd);
            }

            if (!StringUtils.hasLength(mbd.getScope())) {
                mbd.setScope(SCOPE_SINGLETON);
            }

            if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
                mbd.setScope(containingBd.getScope());
            }
            // 放入mergedBeanDefinitions集合
            if (containingBd == null && isCacheBeanMetadata()) {
                this.mergedBeanDefinitions.put(beanName, mbd);
            }
        }
        if (previous != null) {
            copyRelevantMergedBeanDefinitionCaches(previous, mbd);
        }
        return mbd;
    }
}

那么这就是合并父级BeanDefinition属性的实现,可以注意到父级BeanDefinition也仍可以有父级,这样会递归地进行合并。

好了,介绍完这三个BeanDefinition的实现类和合并机制,接着往下看:

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

    for (String beanName : this.beanDefinitionNames) {
        if (!isAlias(beanName)) {
            try {
                // 获取合并后的BeanDefinition定义
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                // Only check bean definition if it is complete.
                if (!mbd.isAbstract() && (allowEagerInit ||
                        (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
                                !requiresEagerInitForType(mbd.getFactoryBeanName()))) {
                    //检查给出的beanName是不是一个FactoryBean对象
                    boolean isFactoryBean = isFactoryBean(beanName, mbd);
                    BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
                    boolean matchFound = false;
                    //是否允许立即初始化
                    boolean allowFactoryBeanInit = allowEagerInit || containsSingleton(beanName);
                    boolean isNonLazyDecorated = dbd != null && !mbd.isLazyInit();
                    //如果不是一个FactoryBean
                    if (!isFactoryBean) {
                        if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
                            //检查类型是否匹配
                            matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
                        }
                    }
                    //如果是一个FactoryBean
                    else  {
                        if (includeNonSingletons || isNonLazyDecorated ||
                                (allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
                            matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
                        }
                        //如果类型不匹配
                        if (!matchFound) {
                            //给Bean加上一个FactoryBean的前缀再匹配。
                            beanName = FACTORY_BEAN_PREFIX + beanName;
                            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.
                LogMessage message = (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);
                onSuppressedException(ex);
            }
        }
    }


    // 检查手动注册的单例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);
}

这个代码里面又涉及一个知识点了:FactoryBean是什么?和BeanFactory有关系吗?

它其实是一个非常简单的接口,代表一个间接获取Bean对象的形式,在Spring中我们可以将一个自定义的FactoryBean对象注册进容器中,然后通过这个对象间接获取需要的Bean对象,可以实现延迟查找:

public interface FactoryBean<T> {

    /**
     * @since 5.2
     */
    String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";

    @Nullable
    // 获取Bean对象
    T getObject() throws Exception;

    @Nullable
    // 获取对象类型
    Class<?> getObjectType();

    // 是否单例
    default boolean isSingleton() {
        return true;
    }
}

最后看一下invokeBeanFactoryPostProcessorsgetBean(String,Class)的实现:

public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
    assertBeanFactoryActive();
    return getBeanFactory().getBean(name, requiredType);
}

首先获取内部的BeanFactory,然后通过BeanFactory获取bean对象:

public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
    return doGetBean(name, requiredType, null, false);
}
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
        @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

    final String beanName = transformedBeanName(name);
    Object bean;

    // 先检查是否有缓存的单例bean(即因循环依赖问题而早期暴露的单例Bean)
    Object sharedInstance = getSingleton(beanName);
    // 如果有缓存的单例bean,不再创建,而是直接返回
    if (sharedInstance != null && args == null) {
        if (logger.isTraceEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                        "' that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
                logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        // 如果Bean是FactoryBean,完成相关处理与转换
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
        // 如果这个多例Bean已经在创建模式中了,说明发生了循环依赖问题(构造器注入),需要报异常
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        // 检查这个bean的BeanDefinition是否存在
        // 如果不存在,检查父级BeanFactory中是否存在
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory) {
                //递归获取Bean对象
                return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                        nameToLookup, requiredType, args, typeCheckOnly);
            }
            else if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else if (requiredType != null) {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
            else {
                return (T) parentBeanFactory.getBean(nameToLookup);
            }
        }

        //创建的bean是否需要类型验证
        if (!typeCheckOnly) {
            //标记该bean已创建
            markBeanAsCreated(beanName);
        }

        try {
            //获取合并后的BeanDefinition
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            //检查是否抽象,抽象报错
            checkMergedBeanDefinition(mbd, beanName, args);

            // 获取该Bean的依赖bean
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    //是否存在循环依赖
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    //将依赖注册到bean
                    registerDependentBean(dep, beanName);
                    try {
                        //获取依赖的bean对象
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            // 如果是单例
            if (mbd.isSingleton()) {
                //创建单例对象,如果该Bean已经在创建模式也会报异常,说明发生了循环依赖
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        destroySingleton(beanName);
                        throw ex;
                    }
                });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }
            //如果是原型对象
            else if (mbd.isPrototype()) {
                // 创建一个新的对象
                Object prototypeInstance = null;
                try {
                    //把该bean标记为正在创建
                    beforePrototypeCreation(beanName);
                    //创建对象
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    //把该bean的正在创建标记清除
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }
            //既不是单例的,也不是原型,基本上就是web服务中的request或session
            else {
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                    Object scopedInstance = scope.get(beanName, () -> {
                        beforePrototypeCreation(beanName);
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        finally {
                            afterPrototypeCreation(beanName);
                        }
                    });
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                }
                catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName,
                            "Scope '" + scopeName + "' is not active for the current thread; consider " +
                            "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                            ex);
                }
            }
        }
        catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
    }

    // 检查创建的bean与需要的类型是否匹配
    if (requiredType != null && !requiredType.isInstance(bean)) {
        try {
            T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
            if (convertedBean == null) {
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
            return convertedBean;
        }
        catch (TypeMismatchException ex) {
            if (logger.isTraceEnabled()) {
                logger.trace("Failed to convert bean '" + name + "' to required type '" +
                        ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}

可以看出不论是单例还是原型对象,都是通过createBean这个方法进行创建,时间不早了,具体创建对象的流程留到下次再说吧。

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/ioc%e5%ae%b9%e5%99%a8%e5%90%af%e5%8a%a8%e6%ba%90%e7%a0%81%e7%ac%ac3%e3%80%814%e3%80%815%e6%ad%a5%e5%88%86%e6%9e%90-%e5%ae%b9%e5%99%a8%e5%8a%a0%e8%bd%bd%e4%ba%86%e5%93%aa%e4%ba%9b%e9%9d%9ebean%e5%af%b9/

发表评论

电子邮件地址不会被公开。