Spring IOC源码解析(09)BeanFactoryUtils

前言

BeanFactoryUtils作为bean工厂操作的工具类,包含了很多的方法。对这些方法的理解,将加深我们后续对BeanFactory实现的分析。

源码解析

/**
 * Convenience methods operating on bean factories, in particular
 * on the {@link ListableBeanFactory} interface.
 *
 * <p>Returns bean counts, bean names or bean instances,
 * taking into account the nesting hierarchy of a bean factory
 * (which the methods defined on the ListableBeanFactory interface don't,
 * in contrast to the methods defined on the BeanFactory interface).
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Chris Beams
 * @since 04.07.2003
 */
public abstract class BeanFactoryUtils {

    /**
     * bean名称的分隔符,当类名或父类名不是唯一时,将通过追加后缀`#1`或`#2`的方式来使得bean名称变得唯一。
     * 通常在内部bean的时候使用。
     * Separator for generated bean names. If a class name or parent name is not
     * unique, "#1", "#2" etc will be appended, until the name becomes unique.
     */
    public static final String GENERATED_BEAN_NAME_SEPARATOR = "#";

    /**
     * 缓存map,工厂bean名称 -> 剥离掉&前缀后的bean名称
     * 即:工厂bean创建的bean的名称
     * Cache from name with factory bean prefix to stripped name without dereference.
     * @since 5.1
     * @see BeanFactory#FACTORY_BEAN_PREFIX
     */
    private static final Map<String, String> transformedBeanNameCache = new ConcurrentHashMap<>();


    /**
     * 根据名称判断是否是一个工厂bean的名称
     * Return whether the given name is a factory dereference
     * (beginning with the factory dereference prefix).
     * @param name the name of the bean
     * @return whether the given name is a factory dereference
     * @see BeanFactory#FACTORY_BEAN_PREFIX
     */
    public static boolean isFactoryDereference(@Nullable String name) {
        return (name != null && name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
    }

    /**
     * 将带有&的所有前缀全部去掉,也就是实际工厂bean创建后的bean的名称
     * 这儿使用了循环遍历,是因为工厂bean创建出来的bean也可能是另外一个工厂bean,以此类推
     * Return the actual bean name, stripping out the factory dereference
     * prefix (if any, also stripping repeated factory prefixes if found).
     * @param name the name of the bean
     * @return the transformed name
     * @see BeanFactory#FACTORY_BEAN_PREFIX
     */
    public static String transformedBeanName(String name) {
        Assert.notNull(name, "'name' must not be null");
        if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
            return name;
        }
        return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
            do {
                beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
            }
            while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
            return beanName;
        });
    }

    /**
     * 判断是否内部生成的bean名称
     * Return whether the given name is a bean name which has been generated
     * by the default naming strategy (containing a "#..." part).
     * @param name the name of the bean
     * @return whether the given name is a generated bean name
     * @see #GENERATED_BEAN_NAME_SEPARATOR
     * @see org.springframework.beans.factory.support.BeanDefinitionReaderUtils#generateBeanName
     * @see org.springframework.beans.factory.support.DefaultBeanNameGenerator
     */
    public static boolean isGeneratedBeanName(@Nullable String name) {
        return (name != null && name.contains(GENERATED_BEAN_NAME_SEPARATOR));
    }

    /**
     * 获取内部bean所在的外部bean
     * Extract the "raw" bean name from the given (potentially generated) bean name,
     * excluding any "#..." suffixes which might have been added for uniqueness.
     * @param name the potentially generated bean name
     * @return the raw bean name
     * @see #GENERATED_BEAN_NAME_SEPARATOR
     */
    public static String originalBeanName(String name) {
        Assert.notNull(name, "'name' must not be null");
        int separatorIndex = name.indexOf(GENERATED_BEAN_NAME_SEPARATOR);
        return (separatorIndex != -1 ? name.substring(0, separatorIndex) : name);
    }


    // Retrieval of bean names

    /**
     * 获取包含祖先在内的所有bean的数量
     * Count all beans in any hierarchy in which this factory participates.
     * Includes counts of ancestor bean factories.
     * <p>Beans that are "overridden" (specified in a descendant factory
     * with the same name) are only counted once.
     * @param lbf the bean factory
     * @return count of beans including those defined in ancestor factories
     * @see #beanNamesIncludingAncestors
     */
    public static int countBeansIncludingAncestors(ListableBeanFactory lbf) {
        return beanNamesIncludingAncestors(lbf).length;
    }

    /**
     * 获取包含祖先在内的所有bean名称数组
     * Return all bean names in the factory, including ancestor factories.
     * @param lbf the bean factory
     * @return the array of matching bean names, or an empty array if none
     * @see #beanNamesForTypeIncludingAncestors
     */
    public static String[] beanNamesIncludingAncestors(ListableBeanFactory lbf) {
        return beanNamesForTypeIncludingAncestors(lbf, Object.class);
    }

    /**
     * 获取包含祖先在内的特定类型的bean名称数组
     * Get all bean names for the given type, including those defined in ancestor
     * factories. Will return unique names in case of overridden bean definitions.
     * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
     * will get initialized. If the object created by the FactoryBean doesn't match,
     * the raw FactoryBean itself will be matched against the type.
     * <p>This version of {@code beanNamesForTypeIncludingAncestors} automatically
     * includes prototypes and FactoryBeans.
     * @param lbf the bean factory
     * @param type the type that beans must match (as a {@code ResolvableType})
     * @return the array of matching bean names, or an empty array if none
     * @since 4.2
     * @see ListableBeanFactory#getBeanNamesForType(ResolvableType)
     */
    public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, ResolvableType type) {
        Assert.notNull(lbf, "ListableBeanFactory must not be null");
        String[] result = lbf.getBeanNamesForType(type);
        // 通过`HierarchicalBeanFactory`类型的工厂继承关系,
        // 从而达到bean名称统计的目的
        if (lbf instanceof HierarchicalBeanFactory) {
            HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
            if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
                String[] parentResult = beanNamesForTypeIncludingAncestors(
                        (ListableBeanFactory) hbf.getParentBeanFactory(), type);
                result = mergeNamesWithParent(result, parentResult, hbf);
            }
        }
        return result;
    }

    /**
     * 获取包含祖先在内的特定类型的bean名称数组,
     * 同时指定是否包含单例,以及是否允许预初始化
     * Get all bean names for the given type, including those defined in ancestor
     * factories. Will return unique names in case of overridden bean definitions.
     * <p>Does consider objects created by FactoryBeans if the "allowEagerInit"
     * flag is set, which means that FactoryBeans will get initialized. If the
     * object created by the FactoryBean doesn't match, the raw FactoryBean itself
     * will be matched against the type. If "allowEagerInit" is not set,
     * only raw FactoryBeans will be checked (which doesn't require initialization
     * of each FactoryBean).
     * @param lbf the bean factory
     * @param type the type that beans must match (as a {@code ResolvableType})
     * @param includeNonSingletons whether to include prototype or scoped beans too
     * or just singletons (also applies to FactoryBeans)
     * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
     * <i>objects created by FactoryBeans</i> (or by factory methods with a
     * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
     * eagerly initialized to determine their type: So be aware that passing in "true"
     * for this flag will initialize FactoryBeans and "factory-bean" references.
     * @return the array of matching bean names, or an empty array if none
     * @since 5.2
     * @see ListableBeanFactory#getBeanNamesForType(ResolvableType, boolean, boolean)
     */
    public static String[] beanNamesForTypeIncludingAncestors(
            ListableBeanFactory lbf, ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {

        Assert.notNull(lbf, "ListableBeanFactory must not be null");
        String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
        if (lbf instanceof HierarchicalBeanFactory) {
            HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
            if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
                String[] parentResult = beanNamesForTypeIncludingAncestors(
                        (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
                result = mergeNamesWithParent(result, parentResult, hbf);
            }
        }
        return result;
    }

    /**
     * 获取包含祖先在内的特定类型的bean名称数组。
     * 这儿的特定类型指的是Class这种类型
     * Get all bean names for the given type, including those defined in ancestor
     * factories. Will return unique names in case of overridden bean definitions.
     * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
     * will get initialized. If the object created by the FactoryBean doesn't match,
     * the raw FactoryBean itself will be matched against the type.
     * <p>This version of {@code beanNamesForTypeIncludingAncestors} automatically
     * includes prototypes and FactoryBeans.
     * @param lbf the bean factory
     * @param type the type that beans must match (as a {@code Class})
     * @return the array of matching bean names, or an empty array if none
     * @see ListableBeanFactory#getBeanNamesForType(Class)
     */
    public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, Class<?> type) {
        Assert.notNull(lbf, "ListableBeanFactory must not be null");
        String[] result = lbf.getBeanNamesForType(type);
        if (lbf instanceof HierarchicalBeanFactory) {
            HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
            if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
                String[] parentResult = beanNamesForTypeIncludingAncestors(
                        (ListableBeanFactory) hbf.getParentBeanFactory(), type);
                result = mergeNamesWithParent(result, parentResult, hbf);
            }
        }
        return result;
    }

    /**
     * 获取包含祖先在内的特定类型的bean名称数组,
     * 同时指定是否包含单例,以及是否允许预初始化,
     * 这儿的特定类型指的是Class这种类型
     * Get all bean names for the given type, including those defined in ancestor
     * factories. Will return unique names in case of overridden bean definitions.
     * <p>Does consider objects created by FactoryBeans if the "allowEagerInit"
     * flag is set, which means that FactoryBeans will get initialized. If the
     * object created by the FactoryBean doesn't match, the raw FactoryBean itself
     * will be matched against the type. If "allowEagerInit" is not set,
     * only raw FactoryBeans will be checked (which doesn't require initialization
     * of each FactoryBean).
     * @param lbf the bean factory
     * @param includeNonSingletons whether to include prototype or scoped beans too
     * or just singletons (also applies to FactoryBeans)
     * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
     * <i>objects created by FactoryBeans</i> (or by factory methods with a
     * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
     * eagerly initialized to determine their type: So be aware that passing in "true"
     * for this flag will initialize FactoryBeans and "factory-bean" references.
     * @param type the type that beans must match
     * @return the array of matching bean names, or an empty array if none
     * @see ListableBeanFactory#getBeanNamesForType(Class, boolean, boolean)
     */
    public static 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);
        if (lbf instanceof HierarchicalBeanFactory) {
            HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
            if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
                String[] parentResult = beanNamesForTypeIncludingAncestors(
                        (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
                result = mergeNamesWithParent(result, parentResult, hbf);
            }
        }
        return result;
    }

    /**
     * 获取包含祖先在内的特定类型(且使用了特定注解)的bean名称数组
     * Get all bean names whose {@code Class} has the supplied {@link Annotation}
     * type, including those defined in ancestor factories, without creating any bean
     * instances yet. Will return unique names in case of overridden bean definitions.
     * @param lbf the bean factory
     * @param annotationType the type of annotation to look for
     * @return the array of matching bean names, or an empty array if none
     * @since 5.0
     * @see ListableBeanFactory#getBeanNamesForAnnotation(Class)
     */
    public static String[] beanNamesForAnnotationIncludingAncestors(
            ListableBeanFactory lbf, Class<? extends Annotation> annotationType) {

        Assert.notNull(lbf, "ListableBeanFactory must not be null");
        String[] result = lbf.getBeanNamesForAnnotation(annotationType);
        if (lbf instanceof HierarchicalBeanFactory) {
            HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
            if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
                String[] parentResult = beanNamesForAnnotationIncludingAncestors(
                        (ListableBeanFactory) hbf.getParentBeanFactory(), annotationType);
                result = mergeNamesWithParent(result, parentResult, hbf);
            }
        }
        return result;
    }


    // Retrieval of bean instances

    /**
     * 获取包含祖先在内的特定类型的bean实例map(key为bean名称,value为bean实例)
     * Return all beans of the given type or subtypes, also picking up beans defined in
     * ancestor bean factories if the current bean factory is a HierarchicalBeanFactory.
     * The returned Map will only contain beans of this type.
     * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
     * will get initialized. If the object created by the FactoryBean doesn't match,
     * the raw FactoryBean itself will be matched against the type.
     * <p><b>Note: Beans of the same name will take precedence at the 'lowest' factory level,
     * i.e. such beans will be returned from the lowest factory that they are being found in,
     * hiding corresponding beans in ancestor factories.</b> This feature allows for
     * 'replacing' beans by explicitly choosing the same bean name in a child factory;
     * the bean in the ancestor factory won't be visible then, not even for by-type lookups.
     * @param lbf the bean factory
     * @param type type of bean to match
     * @return the Map of matching bean instances, or an empty Map if none
     * @throws BeansException if a bean could not be created
     * @see ListableBeanFactory#getBeansOfType(Class)
     */
    public static <T> Map<String, T> beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
            throws BeansException {

        Assert.notNull(lbf, "ListableBeanFactory must not be null");
        Map<String, T> result = new LinkedHashMap<>(4);
        result.putAll(lbf.getBeansOfType(type));
        if (lbf instanceof HierarchicalBeanFactory) {
            HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
            if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
                Map<String, T> parentResult = beansOfTypeIncludingAncestors(
                        (ListableBeanFactory) hbf.getParentBeanFactory(), type);
                parentResult.forEach((beanName, beanInstance) -> {
                    if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
                        result.put(beanName, beanInstance);
                    }
                });
            }
        }
        return result;
    }

    /**
     * 获取包含祖先在内的特定类型的bean实例map(key为bean名称,value为bean实例)
     * 同时指定是否包含单例,以及是否允许预初始化,
     * Return all beans of the given type or subtypes, also picking up beans defined in
     * ancestor bean factories if the current bean factory is a HierarchicalBeanFactory.
     * The returned Map will only contain beans of this type.
     * <p>Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set,
     * which means that FactoryBeans will get initialized. If the object created by the
     * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the
     * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked
     * (which doesn't require initialization of each FactoryBean).
     * <p><b>Note: Beans of the same name will take precedence at the 'lowest' factory level,
     * i.e. such beans will be returned from the lowest factory that they are being found in,
     * hiding corresponding beans in ancestor factories.</b> This feature allows for
     * 'replacing' beans by explicitly choosing the same bean name in a child factory;
     * the bean in the ancestor factory won't be visible then, not even for by-type lookups.
     * @param lbf the bean factory
     * @param type type of bean to match
     * @param includeNonSingletons whether to include prototype or scoped beans too
     * or just singletons (also applies to FactoryBeans)
     * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
     * <i>objects created by FactoryBeans</i> (or by factory methods with a
     * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
     * eagerly initialized to determine their type: So be aware that passing in "true"
     * for this flag will initialize FactoryBeans and "factory-bean" references.
     * @return the Map of matching bean instances, or an empty Map if none
     * @throws BeansException if a bean could not be created
     * @see ListableBeanFactory#getBeansOfType(Class, boolean, boolean)
     */
    public static <T> Map<String, T> beansOfTypeIncludingAncestors(
            ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
            throws BeansException {

        Assert.notNull(lbf, "ListableBeanFactory must not be null");
        Map<String, T> result = new LinkedHashMap<>(4);
        result.putAll(lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit));
        if (lbf instanceof HierarchicalBeanFactory) {
            HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
            if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
                Map<String, T> parentResult = beansOfTypeIncludingAncestors(
                        (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
                parentResult.forEach((beanName, beanInstance) -> {
                    if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
                        result.put(beanName, beanInstance);
                    }
                });
            }
        }
        return result;
    }

    /**
     * 获取包含祖先在内的特定类型的bean实例,这儿通过`uniqueBean`方法校验唯一性
     * Return a single bean of the given type or subtypes, also picking up beans
     * defined in ancestor bean factories if the current bean factory is a
     * HierarchicalBeanFactory. Useful convenience method when we expect a
     * single bean and don't care about the bean name.
     * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
     * will get initialized. If the object created by the FactoryBean doesn't match,
     * the raw FactoryBean itself will be matched against the type.
     * <p>This version of {@code beanOfTypeIncludingAncestors} automatically includes
     * prototypes and FactoryBeans.
     * <p><b>Note: Beans of the same name will take precedence at the 'lowest' factory level,
     * i.e. such beans will be returned from the lowest factory that they are being found in,
     * hiding corresponding beans in ancestor factories.</b> This feature allows for
     * 'replacing' beans by explicitly choosing the same bean name in a child factory;
     * the bean in the ancestor factory won't be visible then, not even for by-type lookups.
     * @param lbf the bean factory
     * @param type type of bean to match
     * @return the matching bean instance
     * @throws NoSuchBeanDefinitionException if no bean of the given type was found
     * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
     * @throws BeansException if the bean could not be created
     * @see #beansOfTypeIncludingAncestors(ListableBeanFactory, Class)
     */
    public static <T> T beanOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
            throws BeansException {

        Map<String, T> beansOfType = beansOfTypeIncludingAncestors(lbf, type);
        return uniqueBean(type, beansOfType);
    }

    /**
     * 获取包含祖先在内的特定类型的bean实例,这儿通过`uniqueBean`方法校验唯一性
     * 同时指定是否包含单例,以及是否允许预初始化,
     * Return a single bean of the given type or subtypes, also picking up beans
     * defined in ancestor bean factories if the current bean factory is a
     * HierarchicalBeanFactory. Useful convenience method when we expect a
     * single bean and don't care about the bean name.
     * <p>Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set,
     * which means that FactoryBeans will get initialized. If the object created by the
     * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the
     * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked
     * (which doesn't require initialization of each FactoryBean).
     * <p><b>Note: Beans of the same name will take precedence at the 'lowest' factory level,
     * i.e. such beans will be returned from the lowest factory that they are being found in,
     * hiding corresponding beans in ancestor factories.</b> This feature allows for
     * 'replacing' beans by explicitly choosing the same bean name in a child factory;
     * the bean in the ancestor factory won't be visible then, not even for by-type lookups.
     * @param lbf the bean factory
     * @param type type of bean to match
     * @param includeNonSingletons whether to include prototype or scoped beans too
     * or just singletons (also applies to FactoryBeans)
     * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
     * <i>objects created by FactoryBeans</i> (or by factory methods with a
     * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
     * eagerly initialized to determine their type: So be aware that passing in "true"
     * for this flag will initialize FactoryBeans and "factory-bean" references.
     * @return the matching bean instance
     * @throws NoSuchBeanDefinitionException if no bean of the given type was found
     * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
     * @throws BeansException if the bean could not be created
     * @see #beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
     */
    public static <T> T beanOfTypeIncludingAncestors(
            ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
            throws BeansException {

        Map<String, T> beansOfType = beansOfTypeIncludingAncestors(lbf, type, includeNonSingletons, allowEagerInit);
        return uniqueBean(type, beansOfType);
    }

    /**
     * 获取包含祖先在内的特定类型的bean实例,这儿通过`uniqueBean`方法校验唯一性
     * Return a single bean of the given type or subtypes, not looking in ancestor
     * factories. Useful convenience method when we expect a single bean and
     * don't care about the bean name.
     * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
     * will get initialized. If the object created by the FactoryBean doesn't match,
     * the raw FactoryBean itself will be matched against the type.
     * <p>This version of {@code beanOfType} automatically includes
     * prototypes and FactoryBeans.
     * @param lbf the bean factory
     * @param type type of bean to match
     * @return the matching bean instance
     * @throws NoSuchBeanDefinitionException if no bean of the given type was found
     * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
     * @throws BeansException if the bean could not be created
     * @see ListableBeanFactory#getBeansOfType(Class)
     */
    public static <T> T beanOfType(ListableBeanFactory lbf, Class<T> type) throws BeansException {
        Assert.notNull(lbf, "ListableBeanFactory must not be null");
        Map<String, T> beansOfType = lbf.getBeansOfType(type);
        return uniqueBean(type, beansOfType);
    }

    /**
     * 获取特定类型的bean实例,这儿通过`uniqueBean`方法校验唯一性
     * 同时指定是否包含单例,以及是否允许预初始化,
     * Return a single bean of the given type or subtypes, not looking in ancestor
     * factories. Useful convenience method when we expect a single bean and
     * don't care about the bean name.
     * <p>Does consider objects created by FactoryBeans if the "allowEagerInit"
     * flag is set, which means that FactoryBeans will get initialized. If the
     * object created by the FactoryBean doesn't match, the raw FactoryBean itself
     * will be matched against the type. If "allowEagerInit" is not set,
     * only raw FactoryBeans will be checked (which doesn't require initialization
     * of each FactoryBean).
     * @param lbf the bean factory
     * @param type type of bean to match
     * @param includeNonSingletons whether to include prototype or scoped beans too
     * or just singletons (also applies to FactoryBeans)
     * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
     * <i>objects created by FactoryBeans</i> (or by factory methods with a
     * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
     * eagerly initialized to determine their type: So be aware that passing in "true"
     * for this flag will initialize FactoryBeans and "factory-bean" references.
     * @return the matching bean instance
     * @throws NoSuchBeanDefinitionException if no bean of the given type was found
     * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
     * @throws BeansException if the bean could not be created
     * @see ListableBeanFactory#getBeansOfType(Class, boolean, boolean)
     */
    public static <T> T beanOfType(
            ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
            throws BeansException {

        Assert.notNull(lbf, "ListableBeanFactory must not be null");
        Map<String, T> beansOfType = lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit);
        return uniqueBean(type, beansOfType);
    }


    /**
     * 合并bean名称,内部通过List的addAll方法实现
     * Merge the given bean names result with the given parent result.
     * @param result the local bean name result
     * @param parentResult the parent bean name result (possibly empty)
     * @param hbf the local bean factory
     * @return the merged result (possibly the local result as-is)
     * @since 4.3.15
     */
    private static String[] mergeNamesWithParent(String[] result, String[] parentResult, HierarchicalBeanFactory hbf) {
        if (parentResult.length == 0) {
            return result;
        }
        List<String> merged = new ArrayList<>(result.length + parentResult.length);
        merged.addAll(Arrays.asList(result));
        for (String beanName : parentResult) {
            if (!merged.contains(beanName) && !hbf.containsLocalBean(beanName)) {
                merged.add(beanName);
            }
        }
        return StringUtils.toStringArray(merged);
    }

    /**
     * 校验map的唯一性
     * Extract a unique bean for the given type from the given Map of matching beans.
     * @param type type of bean to match
     * @param matchingBeans all matching beans found
     * @return the unique bean instance
     * @throws NoSuchBeanDefinitionException if no bean of the given type was found
     * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
     */
    private static <T> T uniqueBean(Class<T> type, Map<String, T> matchingBeans) {
        int count = matchingBeans.size();
        if (count == 1) {
            return matchingBeans.values().iterator().next();
        }
        else if (count > 1) {
            throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
        }
        else {
            throw new NoSuchBeanDefinitionException(type);
        }
    }
}

总结

通过上面我们对源码的分析,我们大致看出此工具类包含以下几类方法:

  1. isFactoryDereference -- 根据名称判断是否是一个工厂bean的名称
  2. transformedBeanName -- 将带有&的所有前缀全部去掉
  3. isGeneratedBeanName -- 判断是否内部生成的bean名称
  4. originalBeanName -- 获取内部bean所在的外部bean
  5. countBeansIncludingAncestors -- 获取包含祖先在内的所有bean的数量
  6. beanNamesForTypeIncludingAncestors -- 获取包含祖先在内的bean名称数组,存在多个重载方法
  7. beansOfTypeIncludingAncestors -- 获取包含祖先在内的bean实例map,存在多个重载方法
  8. beanOfTypeIncludingAncestors -- 获取包含祖先在内的bean实例,存在多个重载方法
  9. beanOfType -- 获取特定类型的bean实例(不包含祖先)

所有这些方法,基本都是对bean名称、bean实例、bean类型的判断和处理,是构成spring ioc的核心工具类方法。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,295评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,928评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,682评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,209评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,237评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,965评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,586评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,487评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,016评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,136评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,271评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,948评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,619评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,139评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,252评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,598评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,267评论 2 358