4

AbstractBeanFactory

AbstractBeanFactory抽象类,继承了FactoryBeanRegistrySupport及实现了ConfigurableBeanFactory接口。

类结构

image.png

字段

// 父类容器
private BeanFactory parentBeanFactory;
// 类加载器
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
// 临时加载器
private ClassLoader tempClassLoader;
// bean的元数据缓存
private boolean cacheBeanMetadata = true;
// bean的表达式解析器
private BeanExpressionResolver beanExpressionResolver;
// 类型转换器
private ConversionService conversionService;
// 属性编辑器
private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4);
// 类的属性编辑器
private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4);
// 类型转换器
private TypeConverter typeConverter;
// 为嵌入的值(如注释属性)添加字符串解析器
private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>();
// 后置处理器
private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
// InstantiationAwareBeanPostProcessors是否已注册
private volatile boolean hasInstantiationAwareBeanPostProcessors;
// DestructionAwareBeanPostProcessors是否已注册
private volatile boolean hasDestructionAwareBeanPostProcessors;
// 作用域
private final Map<String, Scope> scopes = new LinkedHashMap<>(8);
// 提供安全作用域
private SecurityContextProvider securityContextProvider;
// 合并后的BeanDefinition
private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);
// bean实例是否已创建
private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));
// 本地缓存,正在创建的多例bean。这边用本地线程,是因为其他线程创建bean与当前线程不冲突
private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal<>("Prototype beans currently in creation");

方法解析

AbstractBeanFactory

构造函数,父类容器可作为参数传入

public AbstractBeanFactory() {
}

public AbstractBeanFactory(@Nullable BeanFactory parentBeanFactory) {
    this.parentBeanFactory = parentBeanFactory;
}

getBean

实际上都是调用doGetBean的方法

@Override
public Object getBean(String name) throws BeansException {
    return doGetBean(name, null, null, false);
}

@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
    return doGetBean(name, requiredType, null, false);
}

@Override
public Object getBean(String name, Object... args) throws BeansException {
    return doGetBean(name, null, args, false);
}
public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
        throws BeansException {

    return doGetBean(name, requiredType, args, false);
}

doGetBean

doGetBean有四个参数:

  • name:bean的名称
  • requiredType: 返回的类型
  • args: 传递的构造参数
  • typeCheckOnly: 检查类型
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
        @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
    //获取beanName,这边有三种形式,一个是原始的beanName,一个是加了&的,一个是别名
    final String beanName = transformedBeanName(name);
    Object bean;

    // Eagerly check singleton cache for manually registered singletons.
    // 是否已经创建了
    Object sharedInstance = getSingleton(beanName);
    //已经创建了,且没有构造参数,进入这个方法,如果有构造参数,往else走,也就是说不从获取bean,而直接创建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,返回他的getObject
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
        // Fail if we're already creating this bean instance:
        // We're assumably within a circular reference.
        // 没创建过bean或者是多例的情况或者有参数的情况
        // 创建过Prototype的bean,会循环引用,抛出异常,单例才尝试解决循环依赖的问题
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory();
        // 父容器存在,本地没有当前beanName,从父容器取
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            // 处理后,如果是加&,就补上&
            String nameToLookup = originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory) {
                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);
            }
        }

        if (!typeCheckOnly) {
            // typeCheckOnly为false,将beanName放入alreadyCreated中
            markBeanAsCreated(beanName);
        }

        try {
            // 获取BeanDefinition
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            // 抽象类检查
            checkMergedBeanDefinition(mbd, beanName, args);

            // Guarantee initialization of beans that the current bean depends on.
            // 如果有依赖的情况,先初始化依赖的bean
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    // 检查是否循环依赖,a依赖b,b依赖a。包括传递的依赖,比如a依赖b,b依赖c,c依赖a
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    // 注册依赖关系
                    registerDependentBean(dep, beanName);
                    try {
                        // 初始化依赖的bean
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            // Create bean instance.
            // 如果是单例
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        // 创建bean
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        // Explicitly remove instance from singleton cache: It might have been put there
                        // eagerly by the creation process, to allow for circular reference resolution.
                        // Also remove any beans that received a temporary reference to the bean.
                        destroySingleton(beanName);
                        throw ex;
                    }
                });
                // 如果是普通bean,直接返回,是FactoryBean,返回他的getObject
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }

            else if (mbd.isPrototype()) {
                // It's a prototype -> create a new instance.
                Object prototypeInstance = null;
                try {
                    // 加入prototypesCurrentlyInCreation,说明正在创建
                    beforePrototypeCreation(beanName);
                    //创建bean
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    // 移除prototypesCurrentlyInCreation,说明已经创建结束
                    afterPrototypeCreation(beanName);
                }
                // 如果是普通bean,直接返回,是FactoryBean,返回他的getObject
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }

            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;
        }
    }

    // Check if required type matches the type of the actual bean instance.
    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;
}

containsBean

是否已经创建bean或者定义好了bean,包括当前容器以及父容器

public boolean containsBean(String name) {
    String beanName = transformedBeanName(name);
    // 已创建单例bean或者包括bean的定义
    if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
        // 如果不是&开头的,直接返回
        // 如果是&开头的,判断是否是FactoryBean,没有找到从父类找
        return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
    }
    // Not found -> check parent.
    // 当前容器没找到,去父类找
    BeanFactory parentBeanFactory = getParentBeanFactory();
    return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}

isSingleton

指定beanName是否是单例,包括普通的bean和FactoryBean,包括当前容器以及父容器

public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
    String beanName = transformedBeanName(name);
    // 如果已经实例化了
    Object beanInstance = getSingleton(beanName, false);
    if (beanInstance != null) {
        if (beanInstance instanceof FactoryBean) {
            // 是FactoryBean类型,name要&开头或者FactoryBean中isSingleton方法返回为true
            return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean<?>) beanInstance).isSingleton());
        }
        else {
            // 如果不是FactoryBean,name就不能是&开头
            return !BeanFactoryUtils.isFactoryDereference(name);
        }
    }

    // No singleton instance found -> check bean definition.
    // 如果当前容器还没实例化,去父类找
    BeanFactory parentBeanFactory = getParentBeanFactory();
    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
        // No bean definition found in this factory -> delegate to parent.
        return parentBeanFactory.isSingleton(originalBeanName(name));
    }
    // 父类也没有,根据定义来判断是否是单例
    // 获取合并后的BeanDefinition
    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

    // In case of FactoryBean, return singleton status of created object if not a dereference.
    if (mbd.isSingleton()) {
        // 如果定义了是单例,判断是否是FactoryBean,如果是FactoryBean,name就要是&开头
        if (isFactoryBean(beanName, mbd)) {
            if (BeanFactoryUtils.isFactoryDereference(name)) {
                return true;
            }
            // 如果是单例,但是name不是&开头,就重新获取factoryBean,再判断是否是单例
            FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
            return factoryBean.isSingleton();
        }
        else {
            // 如果不是FactoryBean,就不能是&开头
            return !BeanFactoryUtils.isFactoryDereference(name);
        }
    }
    else {
        return false;
    }
}

isPrototype

指定beanName是否是多例,包括普通的bean和FactoryBean,包括当前容器以及父容器

public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
    String beanName = transformedBeanName(name);
    // 有父容器,且没有beanName的定义,从父容器中查找
    BeanFactory parentBeanFactory = getParentBeanFactory();
    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
        // No bean definition found in this factory -> delegate to parent.
        return parentBeanFactory.isPrototype(originalBeanName(name));
    }
    // 没有再从当前容器查找
    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    if (mbd.isPrototype()) {
        // In case of FactoryBean, return singleton status of created object if not a dereference.
        // 如果是普通的bean返回true,如果是&开头的,且是FactoryBean,返回true
        return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd));
    }

    // Singleton or scoped - not a prototype.
    // However, FactoryBean may still produce a prototype object...
    // 如果不是Prototype,且是&开头,&开头就是FactoryBean,FactoryBean是单例的,所以是返回false
    if (BeanFactoryUtils.isFactoryDereference(name)) {
        return false;
    }
    // 如果是FactoryBean,判断是否有Singleton或者Prototype
    if (isFactoryBean(beanName, mbd)) {
        final FactoryBean<?> fb = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
        if (System.getSecurityManager() != null) {
            return AccessController.doPrivileged((PrivilegedAction<Boolean>) () ->
                    ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) || !fb.isSingleton()),
                    getAccessControlContext());
        }
        else {
            return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) ||
                    !fb.isSingleton());
        }
    }
    else {
        return false;
    }
}

isTypeMatch

指定的beanName是否与类型匹配

public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
        String beanName = transformedBeanName(name);

    // Check manually registered singletons.
    // 获取单例
    Object beanInstance = getSingleton(beanName, false);
    // 不为空并且不是NullBean类型
    if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
        if (beanInstance instanceof FactoryBean) {
            if (!BeanFactoryUtils.isFactoryDereference(name)) {
                // 不是&开头,获取FactoryBean的getObjectType类型,再来比较
                Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
                return (type != null && typeToMatch.isAssignableFrom(type));
            }
            else {
                // name是&开头,直接判断类型FactoryBean
                return typeToMatch.isInstance(beanInstance);
            }
        }
        // 普通bean,且没有&开头
        else if (!BeanFactoryUtils.isFactoryDereference(name)) {
            if (typeToMatch.isInstance(beanInstance)) {
                // Direct match for exposed instance?
                return true;
            }
            // 泛型且有beanName的定义
            else if (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) {
                // Generics potentially only match on the target class, not on the proxy...
                // 合并定义
                RootBeanDefinition mbd = 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)) {
                        return false;
                    }
                    if (typeToMatch.isAssignableFrom(targetType)) {
                        return true;
                    }
                }
                ResolvableType resolvableType = mbd.targetType;
                if (resolvableType == null) {
                    resolvableType = mbd.factoryMethodReturnType;
                }
                return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType));
            }
        }
        return false;
    }
    // 已经创建了,但是没有bean的定义,说明是空的注册进来
    else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
        // null instance registered
        return false;
    }

    // No singleton instance found -> check bean definition.
    // 从父类找
    BeanFactory parentBeanFactory = getParentBeanFactory();
    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
        // No bean definition found in this factory -> delegate to parent.
        return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
    }

    // Retrieve corresponding bean definition.
    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

    Class<?> classToMatch = typeToMatch.resolve();
    if (classToMatch == null) {
        classToMatch = FactoryBean.class;
    }
    Class<?>[] typesToMatch = (FactoryBean.class == classToMatch ?
            new Class<?>[] {classToMatch} : new Class<?>[] {FactoryBean.class, classToMatch});

    // Check decorated bean definition, if any: We assume it'll be easier
    // to determine the decorated bean's type than the proxy's type.
    BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
    if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
        RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
        Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
        if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
            return typeToMatch.isAssignableFrom(targetClass);
        }
    }

    Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);
    if (beanType == null) {
        return false;
    }

    // Check bean class whether we're dealing with a FactoryBean.
    if (FactoryBean.class.isAssignableFrom(beanType)) {
        if (!BeanFactoryUtils.isFactoryDereference(name) && beanInstance == null) {
            // If it's a FactoryBean, we want to look at what it creates, not the factory class.
            beanType = getTypeForFactoryBean(beanName, mbd);
            if (beanType == null) {
                return false;
            }
        }
    }
    else if (BeanFactoryUtils.isFactoryDereference(name)) {
        // 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.
        beanType = predictBeanType(beanName, mbd, FactoryBean.class);
        if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) {
            return false;
        }
    }

    ResolvableType resolvableType = mbd.targetType;
    if (resolvableType == null) {
        resolvableType = mbd.factoryMethodReturnType;
    }
    if (resolvableType != null && resolvableType.resolve() == beanType) {
        return typeToMatch.isAssignableFrom(resolvableType);
    }
    return typeToMatch.isAssignableFrom(beanType);
}

public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException {
    // 类型转换后调用上面的方法
    return isTypeMatch(name, ResolvableType.forRawClass(typeToMatch));
}

getType

获取指定beanName的类型

public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
    String beanName = transformedBeanName(name);

    // Check manually registered singletons.
    Object beanInstance = getSingleton(beanName, false);
    // 已经实例化并且不是NullBean
    if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
        // 如果是FactoryBean,且没有&,说明是取FactoryBean的getObjectType类型
        if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
            return getTypeForFactoryBean((FactoryBean<?>) beanInstance);
        }
        else {
            // 直接返回类型
            return beanInstance.getClass();
        }
    }

    // No singleton instance found -> check bean definition.
    // 没有实例过,从父容器看看有没有实例化
    BeanFactory parentBeanFactory = getParentBeanFactory();
    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
        // No bean definition found in this factory -> delegate to parent.
        return parentBeanFactory.getType(originalBeanName(name));
    }
    // 都没有实例化,从定义里查找
    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

    // Check decorated bean definition, if any: We assume it'll be easier
    // to determine the decorated bean's type than the proxy's type.
    BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
    if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
        RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
        Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
        if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
            return targetClass;
        }
    }

    Class<?> beanClass = predictBeanType(beanName, mbd);

    // Check bean class whether we're dealing with a FactoryBean.
    if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
        if (!BeanFactoryUtils.isFactoryDereference(name)) {
            // If it's a FactoryBean, we want to look at what it creates, not at the factory class.
            return getTypeForFactoryBean(beanName, mbd);
        }
        else {
            return beanClass;
        }
    }
    else {
        return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);
    }
}

getAliases

public String[] getAliases(String name) {
    String beanName = transformedBeanName(name);
    List<String> aliases = new ArrayList<>();
    // 如果有&解析后要再加回去
    boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);
    String fullBeanName = beanName;
    if (factoryPrefix) {
        fullBeanName = FACTORY_BEAN_PREFIX + beanName;
    }
    if (!fullBeanName.equals(name)) {
        aliases.add(fullBeanName);
    }
    String[] retrievedAliases = super.getAliases(beanName);
    for (String retrievedAlias : retrievedAliases) {
        String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAlias;
        if (!alias.equals(name)) {
            aliases.add(alias);
        }
    }
    // 没实例化过且没有bean的定义,从父类查找
    if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null) {
            aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));
        }
    }
    return StringUtils.toStringArray(aliases);
}

getParentBeanFactory

获取父容器

public BeanFactory getParentBeanFactory() {
    return this.parentBeanFactory;
}

setParentBeanFactory

设置父容器

public void setParentBeanFactory(@Nullable BeanFactory parentBeanFactory) {
    // 只能设置一个,不能修改
    if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
        throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
    }
    this.parentBeanFactory = parentBeanFactory;
}

containsLocalBean

当前容器是否有指定的bean

public boolean containsLocalBean(String name) {
    String beanName = transformedBeanName(name);
    return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
            (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
}

setBeanClassLoader

getBeanClassLoader

类加载器、临时加载器

// 设置类加载器
public void setBeanClassLoader(@Nullable ClassLoader beanClassLoader) {
    this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());
}
// 获取类加载器
public ClassLoader getBeanClassLoader() {
    return this.beanClassLoader;
}
// 设置临时加载器,如果涉及到加载时编织,通常只指定一个临时类装入器,以确保实际的bean类被尽可能延迟地装入
public void setTempClassLoader(@Nullable ClassLoader tempClassLoader) {
    this.tempClassLoader = tempClassLoader;
}
// 获取临时加载器
public ClassLoader getTempClassLoader() {
    return this.tempClassLoader;
}

setCacheBeanMetadata

isCacheBeanMetadata

bean的元数据缓存,默认为true。如果为false,每次创建bean都要从类加载器获取信息

// 设置是否缓存
public void setCacheBeanMetadata(boolean cacheBeanMetadata) {
    this.cacheBeanMetadata = cacheBeanMetadata;
}

// 获取是否缓存
public boolean isCacheBeanMetadata() {
    return this.cacheBeanMetadata;
}

setBeanExpressionResolver

getBeanExpressionResolver

bean的表达式解析器

// 设置表达式解析器
public void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver) {
    this.beanExpressionResolver = resolver;
}

// 获取表达式解析器
public BeanExpressionResolver getBeanExpressionResolver() {
    return this.beanExpressionResolver;
}

setConversionService

getConversionService

类型转换器

// 设置类型转换器
public void setConversionService(@Nullable ConversionService conversionService) {
    this.conversionService = conversionService;
}

// 获取类型转换器
public ConversionService getConversionService() {
    return this.conversionService;
}

addPropertyEditorRegistrar

getPropertyEditorRegistrars

属性编辑器

// 添加属性编辑器
public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
    Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");
    this.propertyEditorRegistrars.add(registrar);
}
// 获取属性编辑器
public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() {
    return this.propertyEditorRegistrars;
}

registerCustomEditor

类的属性编辑器

// 注册类的属性编辑器
public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) {
    Assert.notNull(requiredType, "Required type must not be null");
    Assert.notNull(propertyEditorClass, "PropertyEditor class must not be null");
    this.customEditors.put(requiredType, propertyEditorClass);
}
// 复制类的属性编辑器
public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) {
    registerCustomEditors(registry);
}
// 获取类的属性编辑器
public Map<Class<?>, Class<? extends PropertyEditor>> getCustomEditors() {
    return this.customEditors;
}

setTypeConverter

getCustomTypeConverter

getTypeConverter

类型转换器

// 设置类型转换器
public void setTypeConverter(TypeConverter typeConverter) {
    this.typeConverter = typeConverter;
}
// 获取自定义的类型转换器,这边直接取类型转换器
protected TypeConverter getCustomTypeConverter() {
    return this.typeConverter;
}
// 获取类型转换器
public TypeConverter getTypeConverter() {
    TypeConverter customConverter = getCustomTypeConverter();
    if (customConverter != null) {
        return customConverter;
    }
    else {
        // Build default TypeConverter, registering custom editors.
        // 没有设值就初始化一个SimpleTypeConverter
        SimpleTypeConverter typeConverter = new SimpleTypeConverter();
        typeConverter.setConversionService(getConversionService());
        registerCustomEditors(typeConverter);
        return typeConverter;
    }
}

addEmbeddedValueResolver

hasEmbeddedValueResolver

resolveEmbeddedValue

为嵌入的值(如注释属性)添加字符串解析器

// 添加
public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
    Assert.notNull(valueResolver, "StringValueResolver must not be null");
    this.embeddedValueResolvers.add(valueResolver);
}
// 是否有
public boolean hasEmbeddedValueResolver() {
    return !this.embeddedValueResolvers.isEmpty();
}

// 解析给定的嵌入值
public String resolveEmbeddedValue(@Nullable String value) {
    if (value == null) {
        return null;
    }
    String result = value;
    for (StringValueResolver resolver : this.embeddedValueResolvers) {
        result = resolver.resolveStringValue(result);
        if (result == null) {
            return null;
        }
    }
    return result;
}

addBeanPostProcessor

getBeanPostProcessorCount

getBeanPostProcessors

// 增加后置处理器
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
    Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
    // Remove from old position, if any
    // 移除旧的,保证顺序
    this.beanPostProcessors.remove(beanPostProcessor);
    // Track whether it is instantiation/destruction aware
    // 如果是下面两个类型,标志位就设置true
    if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
        this.hasInstantiationAwareBeanPostProcessors = true;
    }
    if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
        this.hasDestructionAwareBeanPostProcessors = true;
    }
    // Add to end of list
    this.beanPostProcessors.add(beanPostProcessor);
}
// 获取后置处理器的个数
public int getBeanPostProcessorCount() {
    return this.beanPostProcessors.size();
}
// 获取后置处理器
public List<BeanPostProcessor> getBeanPostProcessors() {
    return this.beanPostProcessors;
}

hasInstantiationAwareBeanPostProcessors

hasDestructionAwareBeanPostProcessors

这两个的值在addBeanPostProcessor时设置

protected boolean hasInstantiationAwareBeanPostProcessors() {
    return this.hasInstantiationAwareBeanPostProcessors;
}
protected boolean hasDestructionAwareBeanPostProcessors() {
    return this.hasDestructionAwareBeanPostProcessors;
}

registerScope

getRegisteredScopeNames

getRegisteredScope

作用域

// 注册作用域
public void registerScope(String scopeName, Scope scope) {
    Assert.notNull(scopeName, "Scope identifier must not be null");
    Assert.notNull(scope, "Scope must not be null");
    // 单例和多例,不允许再注册
    if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) {
        throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");
    }
    Scope previous = this.scopes.put(scopeName, scope);
    if (previous != null && previous != scope) {
        if (logger.isDebugEnabled()) {
            logger.debug("Replacing scope '" + scopeName + "' from [" + previous + "] to [" + scope + "]");
        }
    }
    else {
        if (logger.isTraceEnabled()) {
            logger.trace("Registering scope '" + scopeName + "' with implementation [" + scope + "]");
        }
    }
}
// 获取作用域,除了单例和多例,这两个注册的时候会报错
public String[] getRegisteredScopeNames() {
    return StringUtils.toStringArray(this.scopes.keySet());
}
// 通过名称获取作用域
public Scope getRegisteredScope(String scopeName) {
    Assert.notNull(scopeName, "Scope identifier must not be null");
    return this.scopes.get(scopeName);
}

setSecurityContextProvider

getAccessControlContext

// 设置SecurityContextProvider
public void setSecurityContextProvider(SecurityContextProvider securityProvider) {
    this.securityContextProvider = securityProvider;
}
// 获取安全作用域
public AccessControlContext getAccessControlContext() {
    return (this.securityContextProvider != null ?
            this.securityContextProvider.getAccessControlContext() :
            AccessController.getContext());
}

copyConfigurationFrom

配置复制。复制内容包括所有标准配置设置以及beanpostprocessor、作用域和特定于工厂的内部设置。不应该包含任何实际bean定义的元数据,例如BeanDefinition对象和bean名称别名。

public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
    Assert.notNull(otherFactory, "BeanFactory must not be null");
    setBeanClassLoader(otherFactory.getBeanClassLoader());
    setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
    setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
    setConversionService(otherFactory.getConversionService());
    if (otherFactory instanceof AbstractBeanFactory) {
        AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
        this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
        this.customEditors.putAll(otherAbstractFactory.customEditors);
        this.typeConverter = otherAbstractFactory.typeConverter;
        this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
        this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors ||
                otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;
        this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors ||
                otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
        this.scopes.putAll(otherAbstractFactory.scopes);
        this.securityContextProvider = otherAbstractFactory.securityContextProvider;
    }
    else {
        setTypeConverter(otherFactory.getTypeConverter());
        String[] otherScopeNames = otherFactory.getRegisteredScopeNames();
        for (String scopeName : otherScopeNames) {
            this.scopes.put(scopeName, otherFactory.getRegisteredScope(scopeName));
        }
    }
}

getMergedBeanDefinition

合并bean的定义,包括父类继承下来的

public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {
    String beanName = transformedBeanName(name);
    // Efficiently check whether bean definition exists in this factory.
    // 如果当前容器没有,且父类是ConfigurableBeanFactory类型,去父类找
    if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
        return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName);
    }
    // Resolve merged bean definition locally.
    // 去本地找
    return getMergedLocalBeanDefinition(beanName);
}

isFactoryBean

是否是FactoryBean类型

public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
    // 获取beanName
    String beanName = transformedBeanName(name);
    // 获取实例
    Object beanInstance = getSingleton(beanName, false);
    // 已经实例化直接判断
    if (beanInstance != null) {
        return (beanInstance instanceof FactoryBean);
    }
    // No singleton instance found -> check bean definition.
    // 没有实例话,且父类是ConfigurableBeanFactory,从父类查找
    if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
        // No bean definition found in this factory -> delegate to parent.
        return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
    }
    return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}

isActuallyInCreation

是否正在创建的bean,包括单例和多例

public boolean isActuallyInCreation(String beanName) {
    return (isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName));
}

isPrototypeCurrentlyInCreation

protected boolean isPrototypeCurrentlyInCreation(String beanName) {
    // 当前线程有值,说明有在创建多例
    Object curVal = this.prototypesCurrentlyInCreation.get();
    // 如果相等,或者在set中,说明创建的多例有包括指定的bean
    return (curVal != null &&
            (curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}

beforePrototypeCreation

多例创建前,把beanName加入到prototypesCurrentlyInCreation,如果是string,说明已加入一个,转换为set

protected void beforePrototypeCreation(String beanName) {
    Object curVal = this.prototypesCurrentlyInCreation.get();
    if (curVal == null) {
        this.prototypesCurrentlyInCreation.set(beanName);
    }
    else if (curVal instanceof String) {
        Set<String> beanNameSet = new HashSet<>(2);
        beanNameSet.add((String) curVal);
        beanNameSet.add(beanName);
        this.prototypesCurrentlyInCreation.set(beanNameSet);
    }
    else {
        Set<String> beanNameSet = (Set<String>) curVal;
        beanNameSet.add(beanName);
    }
}

afterPrototypeCreation

多例创建完了,从prototypesCurrentlyInCreation移除

protected void afterPrototypeCreation(String beanName) {
    Object curVal = this.prototypesCurrentlyInCreation.get();
    if (curVal instanceof String) {
        this.prototypesCurrentlyInCreation.remove();
    }
    else if (curVal instanceof Set) {
        Set<String> beanNameSet = (Set<String>) curVal;
        beanNameSet.remove(beanName);
        if (beanNameSet.isEmpty()) {
            this.prototypesCurrentlyInCreation.remove();
        }
    }
}

destroyBean

销毁bean

public void destroyBean(String beanName, Object beanInstance) {
    destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));
}
protected void destroyBean(String beanName, Object bean, RootBeanDefinition mbd) {
    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy();
}
public void destroyScopedBean(String beanName) {
    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    // 单例和多例不能销毁
    if (mbd.isSingleton() || mbd.isPrototype()) {
        throw new IllegalArgumentException(
                "Bean name '" + beanName + "' does not correspond to an object in a mutable scope");
    }
    String scopeName = mbd.getScope();
    // 没有对应作用域的不能删除
    Scope scope = this.scopes.get(scopeName);
    if (scope == null) {
        throw new IllegalStateException("No Scope SPI registered for scope name '" + scopeName + "'");
    }
    // 如果已初始化,就调用销毁的方法
    Object bean = scope.remove(beanName);
    if (bean != null) {
        destroyBean(beanName, bean, mbd);
    }
}

transformedBeanName

获取beanName,有可能传过来的是原始的beanName,有可能是加了&的,有可能是别名。如果是加了&的,先去除,再获取。如果是别名,先递归到最原始的别名,再获取beanName

protected String transformedBeanName(String name) {
    return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}

originalBeanName

获取原始的beanName,如果有&,要加上&

protected String originalBeanName(String name) {
    String beanName = transformedBeanName(name);
    if (name.startsWith(FACTORY_BEAN_PREFIX)) {
        beanName = FACTORY_BEAN_PREFIX + beanName;
    }
    return beanName;
}

initBeanWrapper

初始化BeanWrapper

protected void initBeanWrapper(BeanWrapper bw) {
    bw.setConversionService(getConversionService());
    registerCustomEditors(bw);
}

registerCustomEditors

批量注册

protected void registerCustomEditors(PropertyEditorRegistry registry) {
    PropertyEditorRegistrySupport registrySupport =
            (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
    if (registrySupport != null) {
        registrySupport.useConfigValueEditors();
    }
    if (!this.propertyEditorRegistrars.isEmpty()) {
        for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
            try {
                // 批量注册到propertyEditorRegistrars
                registrar.registerCustomEditors(registry);
            }
            catch (BeanCreationException ex) {
                Throwable rootCause = ex.getMostSpecificCause();
                if (rootCause instanceof BeanCurrentlyInCreationException) {
                    BeanCreationException bce = (BeanCreationException) rootCause;
                    String bceBeanName = bce.getBeanName();
                    if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
                                    "] failed because it tried to obtain currently created bean '" +
                                    ex.getBeanName() + "': " + ex.getMessage());
                        }
                        onSuppressedException(ex);
                        continue;
                    }
                }
                throw ex;
            }
        }
    }
    if (!this.customEditors.isEmpty()) {
        // 批量注册customEditors
        this.customEditors.forEach((requiredType, editorClass) ->
                registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));
    }
}

getMergedLocalBeanDefinition

getMergedBeanDefinition

protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
    // Quick check on the concurrent map first, with minimal locking.
    RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
    // 已经有了,直接返回
    if (mbd != null) {
        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;

        // Check with full lock now in order to enforce the same merged instance.
        if (containingBd == null) {
            mbd = this.mergedBeanDefinitions.get(beanName);
        }

        if (mbd == null) {
            // 没有父类,根据bd类型直接创建或者克隆返回
            if (bd.getParentName() == null) {
                // Use copy of given root bean definition.
                if (bd instanceof RootBeanDefinition) {
                    mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
                }
                else {
                    mbd = new RootBeanDefinition(bd);
                }
            }
            else {
                // Child bean definition: needs to be merged with parent.
                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 an AbstractBeanFactory 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);
            }

            // Set default singleton scope, if not configured before.
            // 默认单例
            if (!StringUtils.hasLength(mbd.getScope())) {
                mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
            }

            // A bean contained in a non-singleton bean cannot be a singleton itself.
            // Let's correct this on the fly here, since this might be the result of
            // parent-child merging for the outer bean, in which case the original inner bean
            // definition will not have inherited the merged outer bean's singleton status.
            if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
                mbd.setScope(containingBd.getScope());
            }

            // Cache the merged bean definition for the time being
            // (it might still get re-merged later on in order to pick up metadata changes)
            // 缓存bean的定义定义
            if (containingBd == null && isCacheBeanMetadata()) {
                this.mergedBeanDefinitions.put(beanName, mbd);
            }
        }

        return mbd;
    }
}

checkMergedBeanDefinition

如果是抽象的,就抛异常

protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args)
        throws BeanDefinitionStoreException {

    if (mbd.isAbstract()) {
        throw new BeanIsAbstractException(beanName);
    }
}

clearMergedBeanDefinition

移除bean的定义

protected void clearMergedBeanDefinition(String beanName) {
    this.mergedBeanDefinitions.remove(beanName);
}

clearMetadataCache

移除还没创建的bean对应的bean定义

public void clearMetadataCache() {
    this.mergedBeanDefinitions.keySet().removeIf(bean -> !isBeanEligibleForMetadataCaching(bean));
}

resolveBeanClass

doResolveBeanClass

protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch)
        throws CannotLoadBeanClassException {

    try {
        // 已经解析过了,直接返回
        if (mbd.hasBeanClass()) {
            return mbd.getBeanClass();
        }
        if (System.getSecurityManager() != null) {
            return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>) () ->
                doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
        }
        else {
            return doResolveBeanClass(mbd, typesToMatch);
        }
    }
    catch (PrivilegedActionException pae) {
        ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
    }
    catch (ClassNotFoundException ex) {
        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
    }
    catch (LinkageError err) {
        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
    }
}

private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
        throws ClassNotFoundException {

    ClassLoader beanClassLoader = getBeanClassLoader();
    ClassLoader dynamicLoader = beanClassLoader;
    boolean freshResolve = false;

    if (!ObjectUtils.isEmpty(typesToMatch)) {
        // When just doing type checks (i.e. not creating an actual instance yet),
        // use the specified temporary class loader (e.g. in a weaving scenario).
        ClassLoader tempClassLoader = getTempClassLoader();
        if (tempClassLoader != null) {
            dynamicLoader = tempClassLoader;
            freshResolve = true;
            if (tempClassLoader instanceof DecoratingClassLoader) {
                DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
                for (Class<?> typeToMatch : typesToMatch) {
                    // 临时加载器排除这些类型
                    dcl.excludeClass(typeToMatch.getName());
                }
            }
        }
    }

    String className = mbd.getBeanClassName();
    if (className != null) {
        // bean的表达式解析器解析
        Object evaluated = evaluateBeanDefinitionString(className, mbd);
        // 类名不一样
        if (!className.equals(evaluated)) {
            // A dynamically resolved expression, supported as of 4.2...
            // 是class类型直接返回
            if (evaluated instanceof Class) {
                return (Class<?>) evaluated;
            }
            // 字符串freshResolve为true
            else if (evaluated instanceof String) {
                className = (String) evaluated;
                freshResolve = true;
            }
            else {
                throw new IllegalStateException("Invalid class name expression result: " + evaluated);
            }
        }
        if (freshResolve) {
            // When resolving against a temporary class loader, exit early in order
            // to avoid storing the resolved Class in the bean definition.
            类命一样,且是字符串
            if (dynamicLoader != null) {
                try {
                    // 类加载器加载
                    return dynamicLoader.loadClass(className);
                }
                catch (ClassNotFoundException ex) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex);
                    }
                }
            }
            // 没有类加载器
            return ClassUtils.forName(className, dynamicLoader);
        }
    }

    // Resolve regularly, caching the result in the BeanDefinition...
    // 解析并缓存在bean的定义中
    return mbd.resolveBeanClass(beanClassLoader);
}

evaluateBeanDefinitionString

protected Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) {
    // bean的表达式解析器为空直接返回value
    if (this.beanExpressionResolver == null) {
        return value;
    }
    // 不为空,取scope,去解析
    Scope scope = null;
    if (beanDefinition != null) {
        String scopeName = beanDefinition.getScope();
        if (scopeName != null) {
            scope = getRegisteredScope(scopeName);
        }
    }
    return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}

predictBeanType

预测bean的类型

protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    // 如果targetType不为空,直接返回
    Class<?> targetType = mbd.getTargetType();
    if (targetType != null) {
        return targetType;
    }
    if (mbd.getFactoryMethodName() != null) {
        return null;
    }
    return resolveBeanClass(mbd, beanName, typesToMatch);
}

isFactoryBean

protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {
    // 获取解析后的类型
    Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);
    // 如果解析的类型不为空,且是FactoryBean,返回true
    return (beanType != null && FactoryBean.class.isAssignableFrom(beanType));
}

getTypeForFactoryBean

// 通过beanName和定义获取FactoryBean的类型

protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
    if (!mbd.isSingleton()) {
        return null;
    }
    try {
        FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
        return getTypeForFactoryBean(factoryBean);
    }
    catch (BeanCreationException ex) {
        if (ex.contains(BeanCurrentlyInCreationException.class)) {
            if (logger.isTraceEnabled()) {
                logger.trace("Bean currently in creation on FactoryBean type check: " + ex);
            }
        }
        else if (mbd.isLazyInit()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Bean creation exception on lazy FactoryBean type check: " + ex);
            }
        }
        else {
            if (logger.isDebugEnabled()) {
                logger.debug("Bean creation exception on non-lazy FactoryBean type check: " + ex);
            }
        }
        onSuppressedException(ex);
        return null;
    }
}

markBeanAsCreated

如果没有加入到alreadyCreated,就清除当前bean的定义,并加入到alreadyCreated

protected void markBeanAsCreated(String beanName) {
    if (!this.alreadyCreated.contains(beanName)) {
        synchronized (this.mergedBeanDefinitions) {
            if (!this.alreadyCreated.contains(beanName)) {
                // Let the bean definition get re-merged now that we're actually creating
                // the bean... just in case some of its metadata changed in the meantime.
                clearMergedBeanDefinition(beanName);
                this.alreadyCreated.add(beanName);
            }
        }
    }
}

cleanupAfterBeanCreationFailure

创建失败后,从alreadyCreated移除

protected void cleanupAfterBeanCreationFailure(String beanName) {
    synchronized (this.mergedBeanDefinitions) {
        this.alreadyCreated.remove(beanName);
    }
}

isBeanEligibleForMetadataCaching

是否已创建

protected boolean isBeanEligibleForMetadataCaching(String beanName) {
    return this.alreadyCreated.contains(beanName);
}

removeSingletonIfCreatedForTypeCheckOnly

移除没有在alreadyCreated中的单例

protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) {
    if (!this.alreadyCreated.contains(beanName)) {
        removeSingleton(beanName);
        return true;
    }
    else {
        return false;
    }
}

hasBeanCreationStarted

是否已经有bean开始创建了,alreadyCreated为空,说明还没创建,不为空,已经创建

protected boolean hasBeanCreationStarted() {
    return !this.alreadyCreated.isEmpty();
}

getObjectForBeanInstance

如果是非FactoryBean的直接返回,如果是FactoryBean的则处理

protected Object getObjectForBeanInstance(
            Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

    // Don't let calling code try to dereference the factory if the bean isn't a factory.
    // 如果beanname是&开头的,这个bean必须是FactoryBean类型
    if (BeanFactoryUtils.isFactoryDereference(name)) {
        if (beanInstance instanceof NullBean) {
            return beanInstance;
        }
        if (!(beanInstance instanceof FactoryBean)) {
            throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
        }
    }

    // Now we have the bean instance, which may be a normal bean or a FactoryBean.
    // If it's a FactoryBean, we use it to create a bean instance, unless the
    // caller actually wants a reference to the factory.
    // 普通bean或者beanname是&开头的,返回beanInstance
    if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
        return beanInstance;
    }

    // 是FactoryBean但是没有&开头的
    Object object = null;
    if (mbd == null) {
        // bean的定义信息是空的,从缓存中拿
        object = getCachedObjectForFactoryBean(beanName);
    }
    if (object == null) {
        //缓存不存在
        // Return bean instance from factory.
        FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
        // Caches object obtained from FactoryBean if it is a singleton.
        // mdb为空,并且已经实例化过
        if (mbd == null && containsBeanDefinition(beanName)) {
            mbd = getMergedLocalBeanDefinition(beanName);
        }
        // 是否是用户定义的,而不是程序本身定义的
        boolean synthetic = (mbd != null && mbd.isSynthetic());
        object = getObjectFromFactoryBean(factory, beanName, !synthetic);//返回factory的getObject方法
    }
    return object;
}

isBeanNameInUse

从别名、bean的定义、依赖判断beanName是否已使用

public boolean isBeanNameInUse(String beanName) {
    return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName);
}

requiresDestruction

确定给定的bean在关闭时是否需要销毁

protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
    return (bean.getClass() != NullBean.class &&
            (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
                    DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
}

registerDisposableBeanIfNecessary

根据scope注册需要销毁的bean

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
    AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
    // 不是多例且需要销毁
    if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
        if (mbd.isSingleton()) {
            // Register a DisposableBean implementation that performs all destruction
            // work for the given bean: DestructionAwareBeanPostProcessors,
            // DisposableBean interface, custom destroy method.
            // 单例模式下需要销毁的bean
            registerDisposableBean(beanName,
                    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
        else {
            // A bean with a custom scope...
            // 自定义scope的处理
            Scope scope = this.scopes.get(mbd.getScope());
            if (scope == null) {
                throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }
            scope.registerDestructionCallback(beanName,
                    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
    }
}

containsBeanDefinition

是否已有指定bean的bean定义

getBeanDefinition

根据指定的bean获取bean的定义

createBean

创建bean


大军
847 声望183 粉丝

学而不思则罔,思而不学则殆