spring学习之源码分析--DefaultListableBeanFactory

DefaultListableBeanFactory

DefaultListableBeanFactory,继承了AbstractAutowireCapableBeanFactory及实现了ConfigurableListableBeanFactory、BeanDefinitionRegistry接口。

类结构

字段

// JSR-330 支持
private static Class javaxInjectProviderClass;
// DefaultListableBeanFactory引用的缓存
private static final Map> serializableFactories = new ConcurrentHashMap<>(8);
// 序列号id
private String serializationId;
// 是否允许用相同的名称重新注册不同的定义
private boolean allowBeanDefinitionOverriding = true;
// 是否允许懒加载
private boolean allowEagerClassLoading = true;
// 依赖排序顺序
private Comparator dependencyComparator;
// 解析器,用于检查bean定义是否为自动装配候选
private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver();
// 依赖类型和自动注入值的映射
private final Map, Object> resolvableDependencies = new ConcurrentHashMap<>(16);
// BeanDefinition和beanName的映射
private final Map beanDefinitionMap = new ConcurrentHashMap<>(256);
// 依赖类型和单例、非单例bean的映射
private final Map, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
// 依赖类型和单例bean的映射
private final Map, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
// bean定义名称列表,按注册顺序排列。
private volatile List beanDefinitionNames = new ArrayList<>(256);
// 手动注册的单例,按注册顺序排列
private volatile Set manualSingletonNames = new LinkedHashSet<>(16);
// 固定配置的缓存的bean定义名数组
private volatile String[] frozenBeanDefinitionNames;
// 是否可以缓存所有bean的bean定义元数据
private volatile boolean configurationFrozen = false; 
 

方法解析

DefaultListableBeanFactory

构造方法

public DefaultListableBeanFactory() {
    super();
}
public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
    super(parentBeanFactory);
}

setSerializationId

getSerializationId

序列号设置,同时设置到serializableFactories中。

public void setSerializationId(@Nullable String serializationId) {
    if (serializationId != null) {
        serializableFactories.put(serializationId, new WeakReference<>(this));
    }
    else if (this.serializationId != null) {
        serializableFactories.remove(this.serializationId);
    }
    this.serializationId = serializationId;
}
public String getSerializationId() {
    return this.serializationId;
}

setAllowBeanDefinitionOverriding

isAllowBeanDefinitionOverriding

setAllowEagerClassLoading

isAllowEagerClassLoading

setDependencyComparator

getDependencyComparator

setAutowireCandidateResolver

getAutowireCandidateResolver

allowAliasOverriding

set、get代码略

copyConfigurationFrom

复制其他配置信息

public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
    super.copyConfigurationFrom(otherFactory);
    if (otherFactory instanceof DefaultListableBeanFactory) {
        DefaultListableBeanFactory otherListableFactory = (DefaultListableBeanFactory) otherFactory;
        this.allowBeanDefinitionOverriding = otherListableFactory.allowBeanDefinitionOverriding;
        this.allowEagerClassLoading = otherListableFactory.allowEagerClassLoading;
        this.dependencyComparator = otherListableFactory.dependencyComparator;
        // A clone of the AutowireCandidateResolver since it is potentially BeanFactoryAware...
        setAutowireCandidateResolver(BeanUtils.instantiateClass(getAutowireCandidateResolver().getClass()));
        // Make resolvable dependencies (e.g. ResourceLoader) available here as well...
        this.resolvableDependencies.putAll(otherListableFactory.resolvableDependencies);
    }
}

getBean

获取bean

public  T getBean(Class requiredType) throws BeansException {
    // 根据class类型获取bean
    return getBean(requiredType, (Object[]) null);
}
public  T getBean(Class requiredType, @Nullable Object... args) throws BeansException {
    Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false);
    if (resolved == null) {
        throw new NoSuchBeanDefinitionException(requiredType);
    }
    return (T) resolved;
}

getBeanProvider

获取bean的提供者

public  ObjectProvider getBeanProvider(Class requiredType) throws BeansException {
    return getBeanProvider(ResolvableType.forRawClass(requiredType));
}
public  ObjectProvider getBeanProvider(ResolvableType requiredType) {
    return new BeanObjectProvider() {
        @Override
        public T getObject() throws BeansException {
            T resolved = resolveBean(requiredType, null, false);
            if (resolved == null) {
                throw new NoSuchBeanDefinitionException(requiredType);
            }
            return resolved;
        }
        @Override
        public T getObject(Object... args) throws BeansException {
            T resolved = resolveBean(requiredType, args, false);
            if (resolved == null) {
                throw new NoSuchBeanDefinitionException(requiredType);
            }
            return resolved;
        }
        @Override
        @Nullable
        public T getIfAvailable() throws BeansException {
            return resolveBean(requiredType, null, false);
        }
        @Override
        @Nullable
        public T getIfUnique() throws BeansException {
            return resolveBean(requiredType, null, true);
        }
        @Override
        public Stream stream() {
            return Arrays.stream(getBeanNamesForTypedStream(requiredType))
                    .map(name -> (T) getBean(name))
                    .filter(bean -> !(bean instanceof NullBean));
        }
        @Override
        public Stream orderedStream() {
            String[] beanNames = getBeanNamesForTypedStream(requiredType);
            Map matchingBeans = new LinkedHashMap<>(beanNames.length);
            for (String beanName : beanNames) {
                Object beanInstance = getBean(beanName);
                if (!(beanInstance instanceof NullBean)) {
                    matchingBeans.put(beanName, (T) beanInstance);
                }
            }
            Stream stream = matchingBeans.values().stream();
            return stream.sorted(adaptOrderComparator(matchingBeans));
        }
    };
}

resolveBean

private  T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) {
    NamedBeanHolder namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull);
    if (namedBean != null) {
        return namedBean.getBeanInstance();
    }
    BeanFactory parent = getParentBeanFactory();
    // 如果父类是DefaultListableBeanFactory,调用父类的resolveBean方法
    if (parent instanceof DefaultListableBeanFactory) {
        return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull);
    }
    else if (parent != null) {
        // 如果父类不是DefaultListableBeanFactory,且不为空,获取父类的bean的提供者
        ObjectProvider parentProvider = parent.getBeanProvider(requiredType);
        if (args != null) {
            // 有参构造
            return parentProvider.getObject(args);
        }
        else {
            // 无参构造,getIfAvailable:实际存在才返回一个实例,*   getIfUnique: 有多个实例时,返回默认的实例(比如primary)
            return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable());
        }
    }
    return null;
}

getBeanNamesForTypedStream

通过ResolvableType获取bean名称

private String[] getBeanNamesForTypedStream(ResolvableType requiredType) {
    return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this, requiredType);
}

containsBeanDefinition

检查此bean工厂是否包含具有指定名称的bean定义。不考虑本工厂可能参与的任何层级

public boolean containsBeanDefinition(String beanName) {
    Assert.notNull(beanName, "Bean name must not be null");
    return this.beanDefinitionMap.containsKey(beanName);
}

getBeanDefinitionCount

获取bean定义的个数

public int getBeanDefinitionCount() {
    return this.beanDefinitionMap.size();
}

getBeanDefinitionNames

不考虑此工厂可能参与的任何层次结构,并且忽略通过bean定义以外的其他方式注册的任何单例bean

public String[] getBeanDefinitionNames() {
    String[] frozenNames = this.frozenBeanDefinitionNames;
    if (frozenNames != null) {
        return frozenNames.clone();
    }
    else {
        return StringUtils.toStringArray(this.beanDefinitionNames);
    }
}

getBeanNamesForType

根据bean定义或factorybean中getObjectType的值判断,返回与给定类型(包括子类)匹配的bean的名称。

public String[] getBeanNamesForType(ResolvableType type) {
    Class resolved = type.resolve();
    if (resolved != null && !type.hasGenerics()) {
        return getBeanNamesForType(resolved, true, true);
    }
    else {
        return doGetBeanNamesForType(type, true, true);
    }
}

public String[] getBeanNamesForType(@Nullable Class type) {
    return getBeanNamesForType(type, true, true);
}

@Override
public String[] getBeanNamesForType(@Nullable Class type, boolean includeNonSingletons, boolean allowEagerInit) {
    if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
        return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
    }
    Map, 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

根据bean定义或factorybean中getObjectType的值判断,返回与给定类型(包括子类)匹配的bean的名称。

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

    // Check all bean definitions.
    // 遍历所有的beanName
    for (String beanName : this.beanDefinitionNames) {
        // Only consider bean as eligible if the bean name
        // is not defined as alias for some other bean.
        // 没有别名
        if (!isAlias(beanName)) {
            try {
                // 合并bean的定义
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                // Only check bean definition if it is complete.
                if (!mbd.isAbstract() && (allowEagerInit ||
                        (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
                                !requiresEagerInitForType(mbd.getFactoryBeanName()))) {
                    // In case of FactoryBean, match object created by FactoryBean.
                    // 是否是FactoryBean
                    boolean isFactoryBean = isFactoryBean(beanName, mbd);
                    BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
                    boolean matchFound =
                            (allowEagerInit || !isFactoryBean ||
                                    (dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) &&
                            (includeNonSingletons ||
                                    (dbd != null ? mbd.isSingleton() : isSingleton(beanName))) &&
                            isTypeMatch(beanName, type);
                    if (!matchFound && isFactoryBean) {
                        // In case of FactoryBean, try to match FactoryBean instance itself next.
                        beanName = FACTORY_BEAN_PREFIX + beanName;
                        matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type);
                    }
                    if (matchFound) {
                        result.add(beanName);
                    }
                }
            }
            catch (CannotLoadBeanClassException ex) {
                if (allowEagerInit) {
                    throw ex;
                }
                // Probably a class name with a placeholder: let's ignore it for type matching purposes.
                if (logger.isTraceEnabled()) {
                    logger.trace("Ignoring bean class loading failure for bean '" + beanName + "'", ex);
                }
                onSuppressedException(ex);
            }
            catch (BeanDefinitionStoreException ex) {
                if (allowEagerInit) {
                    throw ex;
                }
                // Probably some metadata with a placeholder: let's ignore it for type matching purposes.
                if (logger.isTraceEnabled()) {
                    logger.trace("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex);
                }
                onSuppressedException(ex);
            }
        }
    }

    // Check manually registered singletons too.
    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...
            if (logger.isTraceEnabled()) {
                logger.trace("Failed to check manually registered singleton with name '" + beanName + "'", ex);
            }
        }
    }

    return StringUtils.toStringArray(result);
}

requiresEagerInitForType

是否马上返回bean以确定类型

private boolean requiresEagerInitForType(@Nullable String factoryBeanName) {
    return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName));
}

getBeansOfType

获取bean名称和实例的映射

public  Map getBeansOfType(@Nullable Class type) throws BeansException {
    return getBeansOfType(type, true, true);
}

public  Map getBeansOfType(@Nullable Class type, boolean includeNonSingletons, boolean allowEagerInit)
        throws BeansException {
    // 根据类型获取到bean名称
    String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
    Map result = new LinkedHashMap<>(beanNames.length);
    // 遍历所有名称,通过bean名称获取实例,如果不是NullBean加入到result
    for (String beanName : beanNames) {
        try {
            Object beanInstance = getBean(beanName);
            if (!(beanInstance instanceof NullBean)) {
                result.put(beanName, (T) beanInstance);
            }
        }
        catch (BeanCreationException ex) {
            Throwable rootCause = ex.getMostSpecificCause();
            if (rootCause instanceof BeanCurrentlyInCreationException) {
                BeanCreationException bce = (BeanCreationException) rootCause;
                String exBeanName = bce.getBeanName();
                if (exBeanName != null && isCurrentlyInCreation(exBeanName)) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Ignoring match to currently created bean '" + exBeanName + "': " +
                                ex.getMessage());
                    }
                    onSuppressedException(ex);
                    // Ignore: indicates a circular reference when autowiring constructors.
                    // We want to find matches other than the currently created bean itself.
                    continue;
                }
            }
            throw ex;
        }
    }
    return result;
}

getBeanNamesForAnnotation

根据注解获取bean的名称

public String[] getBeanNamesForAnnotation(Class annotationType) {
    List result = new ArrayList<>();
    // 遍历所有的bean的,把不是抽象类的,以及有annotationType注解的加入到result
    for (String beanName : this.beanDefinitionNames) {
        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        if (!beanDefinition.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) {
            result.add(beanName);
        }
    }
    // 遍历所有的manualSingletonNames,把没有加入到result的以及有annotationType注解的加入到result
    for (String beanName : this.manualSingletonNames) {
        if (!result.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) {
            result.add(beanName);
        }
    }
    return StringUtils.toStringArray(result);
}

getBeansWithAnnotation

根据注解获取bean的实例

public Map getBeansWithAnnotation(Class annotationType) {
    // 根据注解获取bean的名称
    String[] beanNames = getBeanNamesForAnnotation(annotationType);
    Map result = new LinkedHashMap<>(beanNames.length);
    // 遍历bean的名称,获取bean的实例
    for (String beanName : beanNames) {
        Object beanInstance = getBean(beanName);
        if (!(beanInstance instanceof NullBean)) {
            result.put(beanName, beanInstance);
        }
    }
    return result;
}

findAnnotationOnBean

根据beanName获取注解

public  A findAnnotationOnBean(String beanName, Class annotationType)
        throws NoSuchBeanDefinitionException {

    A ann = null;
    // 获取class
    Class beanType = getType(beanName);
    if (beanType != null) {
        // class不为空,获取注解
        ann = AnnotationUtils.findAnnotation(beanType, annotationType);
    }
    // 没获取到注解,且有定义过,从定义里的beanClass获取
    if (ann == null && containsBeanDefinition(beanName)) {
        BeanDefinition bd = getMergedBeanDefinition(beanName);
        if (bd instanceof AbstractBeanDefinition) {
            AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
            if (abd.hasBeanClass()) {
                ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType);
            }
        }
    }
    return ann;
}

registerResolvableDependency

注册依赖类型和自动注入值

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

isAutowireCandidate

指定的bean是否是自动注入的候选

public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
        throws NoSuchBeanDefinitionException {

    return isAutowireCandidate(beanName, descriptor, getAutowireCandidateResolver());
}

protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
        throws NoSuchBeanDefinitionException {

    String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
    // 定义过的,从定义里找
    if (containsBeanDefinition(beanDefinitionName)) {
        return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver);
    }
    // 创建过的单例,重新创建RootBeanDefinition
    else if (containsSingleton(beanName)) {
        return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
    }
    // 都没找到,从父类找
    BeanFactory parent = getParentBeanFactory();
    if (parent instanceof DefaultListableBeanFactory) {
        // No bean definition found in this factory -> delegate to parent.
        return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver);
    }
    else if (parent instanceof ConfigurableListableBeanFactory) {
        // If no DefaultListableBeanFactory, can't pass the resolver along.
        return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor);
    }
    else {
        return true;
    }
}

protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd,
        DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {

    String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
    // 解析
    resolveBeanClass(mbd, beanDefinitionName);
    if (mbd.isFactoryMethodUnique && mbd.factoryMethodToIntrospect == null) {
        new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd);
    }
    // 从别名里找
    return resolver.isAutowireCandidate(
            new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor);
}

getBeanDefinition

从beanDefinitionMap找bean的定义

public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
    BeanDefinition bd = this.beanDefinitionMap.get(beanName);
    if (bd == null) {
        if (logger.isTraceEnabled()) {
            logger.trace("No bean named '" + beanName + "' found in " + this);
        }
        throw new NoSuchBeanDefinitionException(beanName);
    }
    return bd;
}

getBeanNamesIterator

获取bean的迭代名称,包括自定的和手动注册的

public Iterator getBeanNamesIterator() {
    CompositeIterator iterator = new CompositeIterator<>();
    iterator.add(this.beanDefinitionNames.iterator());
    iterator.add(this.manualSingletonNames.iterator());
    return iterator;
}

clearMetadataCache

public void clearMetadataCache() {
    super.clearMetadataCache();
    clearByTypeCache();
}

freezeConfiguration

冻结当前的bean的信息

public void freezeConfiguration() {
    this.configurationFrozen = true;
    this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
}

isConfigurationFrozen

public boolean isConfigurationFrozen() {
    return this.configurationFrozen;
}

isBeanEligibleForMetadataCaching

是否已经冻结了或者是否已创建

protected boolean isBeanEligibleForMetadataCaching(String beanName) {
    return (this.configurationFrozen || super.isBeanEligibleForMetadataCaching(beanName));
}

preInstantiateSingletons

确保实例化了所有非lazy-init单例

public void preInstantiateSingletons() throws BeansException {
    if (logger.isTraceEnabled()) {
        logger.trace("Pre-instantiating singletons in " + this);
    }

    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    List beanNames = new ArrayList<>(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    // 遍历beanNames
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 不是抽象的,并且是单例且没有懒加载
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            //FactoryBean的情况
            if (isFactoryBean(beanName)) {
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
                    final FactoryBean factory = (FactoryBean) bean;
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged((PrivilegedAction)
                                        ((SmartFactoryBean) factory)::isEagerInit,
                                getAccessControlContext());
                    }
                    else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean) factory).isEagerInit());
                    }
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            }
            else {
                // 直接获取
                getBean(beanName);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    // 获取单例bean后,如果是SmartInitializingSingleton类型,再调用afterSingletonsInstantiated方法
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction) () -> {
                    smartSingleton.afterSingletonsInstantiated();
                    return null;
                }, getAccessControlContext());
            }
            else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
} 
 

registerBeanDefinition

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
        throws BeanDefinitionStoreException {

    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.notNull(beanDefinition, "BeanDefinition must not be null");
    
    if (beanDefinition instanceof AbstractBeanDefinition) {
        try {
            ((AbstractBeanDefinition) beanDefinition).validate();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                    "Validation of bean definition failed", ex);
        }
    }
    // 获取bean的定义
    BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
    if (existingDefinition != null) {
        // 存在的情况
        if (!isAllowBeanDefinitionOverriding()) {
            throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
        }
        else if (existingDefinition.getRole() < beanDefinition.getRole()) {
            // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
            if (logger.isInfoEnabled()) {
                logger.info("Overriding user-defined bean definition for bean '" + beanName +
                        "' with a framework-generated bean definition: replacing [" +
                        existingDefinition + "] with [" + beanDefinition + "]");
            }
        }
        else if (!beanDefinition.equals(existingDefinition)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Overriding bean definition for bean '" + beanName +
                        "' with a different definition: replacing [" + existingDefinition +
                        "] with [" + beanDefinition + "]");
            }
        }
        else {
            if (logger.isTraceEnabled()) {
                logger.trace("Overriding bean definition for bean '" + beanName +
                        "' with an equivalent definition: replacing [" + existingDefinition +
                        "] with [" + beanDefinition + "]");
            }
        }
        this.beanDefinitionMap.put(beanName, beanDefinition);
    }
    else {
        // 不存在的情况,有bean创建了
        if (hasBeanCreationStarted()) {
            // Cannot modify startup-time collection elements anymore (for stable iteration)
            // 加锁
            synchronized (this.beanDefinitionMap) {
                // 设置以下三个信息
                this.beanDefinitionMap.put(beanName, beanDefinition);
                List updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
                updatedDefinitions.addAll(this.beanDefinitionNames);
                updatedDefinitions.add(beanName);
                this.beanDefinitionNames = updatedDefinitions;
                if (this.manualSingletonNames.contains(beanName)) {
                    Set updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
                    updatedSingletons.remove(beanName);
                    this.manualSingletonNames = updatedSingletons;
                }
            }
        }
        else {
            // bean还没创建,赶紧设置以下三个信息
            // Still in startup registration phase
            this.beanDefinitionMap.put(beanName, beanDefinition);
            this.beanDefinitionNames.add(beanName);
            this.manualSingletonNames.remove(beanName);
        }
        this.frozenBeanDefinitionNames = null;
    }

    if (existingDefinition != null || containsSingleton(beanName)) {
        resetBeanDefinition(beanName);
    }
}

removeBeanDefinition

public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
    Assert.hasText(beanName, "'beanName' must not be empty");
    // 移除
    BeanDefinition bd = this.beanDefinitionMap.remove(beanName);
    // 为空说明之前不存在
    if (bd == null) {
        if (logger.isTraceEnabled()) {
            logger.trace("No bean named '" + beanName + "' found in " + this);
        }
        throw new NoSuchBeanDefinitionException(beanName);
    }
    // 已经创建bean了,要加锁
    if (hasBeanCreationStarted()) {
        // Cannot modify startup-time collection elements anymore (for stable iteration)
        synchronized (this.beanDefinitionMap) {
            List updatedDefinitions = new ArrayList<>(this.beanDefinitionNames);
            updatedDefinitions.remove(beanName);
            this.beanDefinitionNames = updatedDefinitions;
        }
    }
    else {
        // Still in startup registration phase
        // 还没创建,直接移除
        this.beanDefinitionNames.remove(beanName);
    }
    this.frozenBeanDefinitionNames = null;

    resetBeanDefinition(beanName);
}

resetBeanDefinition

重置bean的定义

protected void resetBeanDefinition(String beanName) {
    // Remove the merged bean definition for the given bean, if already created.
    // bean定义删除
    clearMergedBeanDefinition(beanName);

    // Remove corresponding bean from singleton cache, if any. Shouldn't usually
    // be necessary, rather just meant for overriding a context's default beans
    // (e.g. the default StaticMessageSource in a StaticApplicationContext).
    // bean销毁
    destroySingleton(beanName);

    // Notify all post-processors that the specified bean definition has been reset.
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        if (processor instanceof MergedBeanDefinitionPostProcessor) {
            ((MergedBeanDefinitionPostProcessor) processor).resetBeanDefinition(beanName);
        }
    }

    // Reset all bean definitions that have the given bean as parent (recursively).
    // 子类重置
    for (String bdName : this.beanDefinitionNames) {
        if (!beanName.equals(bdName)) {
            BeanDefinition bd = this.beanDefinitionMap.get(bdName);
            if (beanName.equals(bd.getParentName())) {
                resetBeanDefinition(bdName);
            }
        }
    }
}

registerSingleton

注册单例,手动注册的单例,保存在manualSingletonNames

public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
    super.registerSingleton(beanName, singletonObject);

    if (hasBeanCreationStarted()) {
        // Cannot modify startup-time collection elements anymore (for stable iteration)
        synchronized (this.beanDefinitionMap) {
            if (!this.beanDefinitionMap.containsKey(beanName)) {
                Set updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames.size() + 1);
                updatedSingletons.addAll(this.manualSingletonNames);
                updatedSingletons.add(beanName);
                this.manualSingletonNames = updatedSingletons;
            }
        }
    }
    else {
        // Still in startup registration phase
        if (!this.beanDefinitionMap.containsKey(beanName)) {
            this.manualSingletonNames.add(beanName);
        }
    }

    clearByTypeCache();
}

destroySingleton

销毁bean,还要移除manualSingletonNames的bean

public void destroySingleton(String beanName) {
    super.destroySingleton(beanName);
    this.manualSingletonNames.remove(beanName);
    clearByTypeCache();
}

destroySingletons

销毁所有bean,还要移除manualSingletonNames的所有bean

public void destroySingletons() {
    super.destroySingletons();
    this.manualSingletonNames.clear();
    clearByTypeCache();
}

clearByTypeCache

清除依赖类型的映射

private void clearByTypeCache() {
    this.allBeanNamesByType.clear();
    this.singletonBeanNamesByType.clear();
}

resolveNamedBean

通过类型解析bean

public  NamedBeanHolder resolveNamedBean(Class requiredType) throws BeansException {
    NamedBeanHolder namedBean = resolveNamedBean(ResolvableType.forRawClass(requiredType), null, false);
    if (namedBean != null) {
        return namedBean;
    }
    // 为空去父类查找
    BeanFactory parent = getParentBeanFactory();
    if (parent instanceof AutowireCapableBeanFactory) {
        return ((AutowireCapableBeanFactory) parent).resolveNamedBean(requiredType);
    }
    throw new NoSuchBeanDefinitionException(requiredType);
}

private  NamedBeanHolder resolveNamedBean(
        ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) throws BeansException {

    Assert.notNull(requiredType, "Required type must not be null");
    // 获取候选bean
    String[] candidateNames = getBeanNamesForType(requiredType);

    if (candidateNames.length > 1) {
        List autowireCandidates = new ArrayList<>(candidateNames.length);
        for (String beanName : candidateNames) {
            if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) {
                autowireCandidates.add(beanName);
            }
        }
        if (!autowireCandidates.isEmpty()) {
            candidateNames = StringUtils.toStringArray(autowireCandidates);
        }
    }
    // 只有一个候选,就确定是这个了
    if (candidateNames.length == 1) {
        String beanName = candidateNames[0];
        return new NamedBeanHolder<>(beanName, (T) getBean(beanName, requiredType.toClass(), args));
    }
    else if (candidateNames.length > 1) {
        Map candidates = new LinkedHashMap<>(candidateNames.length);
        for (String beanName : candidateNames) {
            // 无参,直接获取bean的类型
            if (containsSingleton(beanName) && args == null) {
                Object beanInstance = getBean(beanName);
                candidates.put(beanName, (beanInstance instanceof NullBean ? null : beanInstance));
            }
            else {
                // 有参,通过beanName获取类型
                candidates.put(beanName, getType(beanName));
            }
        }
        // 获取主要的一个
        String candidateName = determinePrimaryCandidate(candidates, requiredType.toClass());
        if (candidateName == null) {
            // 没获取到,从最高级的获取
            candidateName = determineHighestPriorityCandidate(candidates, requiredType.toClass());
        }
        if (candidateName != null) {
            // 获取到了,创建一个NamedBeanHolder返回
            Object beanInstance = candidates.get(candidateName);
            if (beanInstance == null || beanInstance instanceof Class) {
                beanInstance = getBean(candidateName, requiredType.toClass(), args);
            }
            return new NamedBeanHolder<>(candidateName, (T) beanInstance);
        }
        if (!nonUniqueAsNull) {
            throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet());
        }
    }

    return null;
}

resolveDependency

根据工厂中定义的bean解析指定的依赖项

public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
        @Nullable Set autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

    descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
    if (Optional.class == descriptor.getDependencyType()) {
        return createOptionalDependency(descriptor, requestingBeanName);
    }
    else if (ObjectFactory.class == descriptor.getDependencyType() ||
            ObjectProvider.class == descriptor.getDependencyType()) {
        return new DependencyObjectProvider(descriptor, requestingBeanName);
    }
    else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
        return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
    }
    else {
        Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
                descriptor, requestingBeanName);
        if (result == null) {
            result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
        return result;
    }
}

doResolveDependency

根据工厂中定义的bean解析指定的依赖项

public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
        @Nullable Set autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

    InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
    try {
        // spring第一次创建依赖的时候,会存放在shortcut,后面就不用再解析了
        Object shortcut = descriptor.resolveShortcut(this);
        if (shortcut != null) {
            return shortcut;
        }
        // 获取注入属性的类型
        Class type = descriptor.getDependencyType();
        // 处理@Value的值
        Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
        if (value != null) {
            // 解析value
            if (value instanceof String) {
                String strVal = resolveEmbeddedValue((String) value);
                BeanDefinition bd = (beanName != null && containsBean(beanName) ?
                        getMergedBeanDefinition(beanName) : null);
                value = evaluateBeanDefinitionString(strVal, bd);
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            try {
                return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
            }
            catch (UnsupportedOperationException ex) {
                // A custom TypeConverter which does not support TypeDescriptor resolution...
                return (descriptor.getField() != null ?
                        converter.convertIfNecessary(value, type, descriptor.getField()) :
                        converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
            }
        }
        // 对数组容器的处理,
        Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
        if (multipleBeans != null) {
            return multipleBeans;
        }
        // 对非数组、容器对象的处理,键值对
        Map matchingBeans = findAutowireCandidates(beanName, type, descriptor);
        if (matchingBeans.isEmpty()) {
            // 为空,且required为true,抛异常
            if (isRequired(descriptor)) {
                raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
            }
            return null;
        }

        String autowiredBeanName;
        Object instanceCandidate;
        // 有多个的情况,筛选一个
        if (matchingBeans.size() > 1) {
            autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
            if (autowiredBeanName == null) {
                if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
                    return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
                }
                else {
                    // In case of an optional Collection/Map, silently ignore a non-unique case:
                    // possibly it was meant to be an empty collection of multiple regular beans
                    // (before 4.3 in particular when we didn't even look for collection beans).
                    return null;
                }
            }
            instanceCandidate = matchingBeans.get(autowiredBeanName);
        }
        else {
            // We have exactly one match.
            // 只有一个,直接返回
            Map.Entry entry = matchingBeans.entrySet().iterator().next();
            autowiredBeanName = entry.getKey();
            instanceCandidate = entry.getValue();
        }

        if (autowiredBeanNames != null) {
            autowiredBeanNames.add(autowiredBeanName);
        }
        if (instanceCandidate instanceof Class) {
            instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
        }
        Object result = instanceCandidate;
        if (result instanceof NullBean) {
            if (isRequired(descriptor)) {
                raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
            }
            result = null;
        }
        if (!ClassUtils.isAssignableValue(type, result)) {
            throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
        }
        return result;
    }
    finally {
        ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
    }
}

resolveMultipleBeans

数组容器的情况

private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName,
        @Nullable Set autowiredBeanNames, @Nullable TypeConverter typeConverter) {
    
    final Class type = descriptor.getDependencyType();
    
    if (descriptor instanceof StreamDependencyDescriptor) {
        Map matchingBeans = findAutowireCandidates(beanName, type, descriptor);
        if (autowiredBeanNames != null) {
            autowiredBeanNames.addAll(matchingBeans.keySet());
        }
        Stream stream = matchingBeans.keySet().stream()
                .map(name -> descriptor.resolveCandidate(name, type, this))
                .filter(bean -> !(bean instanceof NullBean));
        if (((StreamDependencyDescriptor) descriptor).isOrdered()) {
            stream = stream.sorted(adaptOrderComparator(matchingBeans));
        }
        return stream;
    }
    else if (type.isArray()) {
        // 数组的情况
        Class componentType = type.getComponentType();
        ResolvableType resolvableType = descriptor.getResolvableType();
        Class resolvedArrayType = resolvableType.resolve(type);
        if (resolvedArrayType != type) {
            componentType = resolvableType.getComponentType().resolve();
        }
        if (componentType == null) {
            return null;
        }
        Map matchingBeans = findAutowireCandidates(beanName, componentType,
                new MultiElementDescriptor(descriptor));
        if (matchingBeans.isEmpty()) {
            return null;
        }
        if (autowiredBeanNames != null) {
            autowiredBeanNames.addAll(matchingBeans.keySet());
        }
        TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
        Object result = converter.convertIfNecessary(matchingBeans.values(), resolvedArrayType);
        if (result instanceof Object[]) {
            Comparator comparator = adaptDependencyComparator(matchingBeans);
            if (comparator != null) {
                Arrays.sort((Object[]) result, comparator);
            }
        }
        return result;
    }
    else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
        // 容器的情况
        Class elementType = descriptor.getResolvableType().asCollection().resolveGeneric();
        if (elementType == null) {
            return null;
        }
        Map matchingBeans = findAutowireCandidates(beanName, elementType,
                new MultiElementDescriptor(descriptor));
        if (matchingBeans.isEmpty()) {
            return null;
        }
        if (autowiredBeanNames != null) {
            autowiredBeanNames.addAll(matchingBeans.keySet());
        }
        TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
        Object result = converter.convertIfNecessary(matchingBeans.values(), type);
        if (result instanceof List) {
            Comparator comparator = adaptDependencyComparator(matchingBeans);
            if (comparator != null) {
                ((List) result).sort(comparator);
            }
        }
        return result;
    }
    else if (Map.class == type) {
        // map的情况
        ResolvableType mapType = descriptor.getResolvableType().asMap();
        Class keyType = mapType.resolveGeneric(0);
        if (String.class != keyType) {
            return null;
        }
        Class valueType = mapType.resolveGeneric(1);
        if (valueType == null) {
            return null;
        }
        Map matchingBeans = findAutowireCandidates(beanName, valueType,
                new MultiElementDescriptor(descriptor));
        if (matchingBeans.isEmpty()) {
            return null;
        }
        if (autowiredBeanNames != null) {
            autowiredBeanNames.addAll(matchingBeans.keySet());
        }
        return matchingBeans;
    }
    else {
        return null;
    }
} 
 

isRequired

Required是否为true

private boolean isRequired(DependencyDescriptor descriptor) {
    return getAutowireCandidateResolver().isRequired(descriptor);
}

indicatesMultipleBeans

注入属性是数组或者容器

private boolean indicatesMultipleBeans(Class type) {
    return (type.isArray() || (type.isInterface() &&
            (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type))));
}

adaptDependencyComparator

private Comparator adaptDependencyComparator(Map matchingBeans) {
    Comparator comparator = getDependencyComparator();
    if (comparator instanceof OrderComparator) {
        return ((OrderComparator) comparator).withSourceProvider(
                createFactoryAwareOrderSourceProvider(matchingBeans));
    }
    else {
        return comparator;
    }
} 
 

adaptOrderComparator

private Comparator adaptOrderComparator(Map matchingBeans) {
    Comparator dependencyComparator = getDependencyComparator();
    OrderComparator comparator = (dependencyComparator instanceof OrderComparator ?
            (OrderComparator) dependencyComparator : OrderComparator.INSTANCE);
    return comparator.withSourceProvider(createFactoryAwareOrderSourceProvider(matchingBeans));
} 
 

createFactoryAwareOrderSourceProvider

private OrderComparator.OrderSourceProvider createFactoryAwareOrderSourceProvider(Map beans) {
    IdentityHashMap instancesToBeanNames = new IdentityHashMap<>();
    beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName));
    return new FactoryAwareOrderSourceProvider(instancesToBeanNames);
}

findAutowireCandidates

protected Map findAutowireCandidates(
        @Nullable String beanName, Class requiredType, DependencyDescriptor descriptor) {
    // 获取批评类型的beanName
    String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
            this, requiredType, true, descriptor.isEager());
    // 存放结果
    Map result = new LinkedHashMap<>(candidateNames.length);
    // 如果遍历的类型是指定的类型或者子类的话,报错在result
    for (Map.Entry, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
        Class autowiringType = classObjectEntry.getKey();
        if (autowiringType.isAssignableFrom(requiredType)) {
            Object autowiringValue = classObjectEntry.getValue();
            autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
            if (requiredType.isInstance(autowiringValue)) {
                result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
                break;
            }
        }
    }
    for (String candidate : candidateNames) {
        // 如果不是自引用,且符合注入的条件
        if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
            addCandidateEntry(result, candidate, descriptor, requiredType);
        }
    }
    // result为空
    if (result.isEmpty()) {
        // 注入属性是数组和容器类型,对泛型检查
        boolean multiple = indicatesMultipleBeans(requiredType);
        // Consider fallback matches if the first pass failed to find anything...
        DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
        for (String candidate : candidateNames) {
            if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
                    (!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
                addCandidateEntry(result, candidate, descriptor, requiredType);
            }
        }
        // 为空,且不是数组和容器类型,添加自引用
        if (result.isEmpty() && !multiple) {
            // Consider self references as a final pass...
            // but in the case of a dependency collection, not the very same bean itself.
            for (String candidate : candidateNames) {
                if (isSelfReference(beanName, candidate) &&
                        (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
                        isAutowireCandidate(candidate, fallbackDescriptor)) {
                    addCandidateEntry(result, candidate, descriptor, requiredType);
                }
            }
        }
    }
    return result;
}

addCandidateEntry

加入到candidate,在主候选项选择之前防止早期的bean初始化。

private void addCandidateEntry(Map candidates, String candidateName,
        DependencyDescriptor descriptor, Class requiredType) {

    if (descriptor instanceof MultiElementDescriptor) {
        Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this);
        if (!(beanInstance instanceof NullBean)) {
            candidates.put(candidateName, beanInstance);
        }
    }
    else if (containsSingleton(candidateName) || (descriptor instanceof StreamDependencyDescriptor &&
            ((StreamDependencyDescriptor) descriptor).isOrdered())) {
        Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this);
        candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance));
    }
    else {
        candidates.put(candidateName, getType(candidateName));
    }
}

determineAutowireCandidate

protected String determineAutowireCandidate(Map candidates, DependencyDescriptor descriptor) {
    Class requiredType = descriptor.getDependencyType();
    // 如果是主要的,直接返回
    String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
    if (primaryCandidate != null) {
        return primaryCandidate;
    }
    // 如果是最高级的,直接返回
    String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
    if (priorityCandidate != null) {
        return priorityCandidate;
    }
    // Fallback
    // 如果不是主要和最高级的
    for (Map.Entry entry : candidates.entrySet()) {
        String candidateName = entry.getKey();
        Object beanInstance = entry.getValue();
        if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
                matchesBeanName(candidateName, descriptor.getDependencyName())) {
            return candidateName;
        }
    }
    return null;
}

determinePrimaryCandidate

如果是主要的情况

protected String determinePrimaryCandidate(Map candidates, Class requiredType) {
    String primaryBeanName = null;
    for (Map.Entry entry : candidates.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        if (isPrimary(candidateBeanName, beanInstance)) {
            if (primaryBeanName != null) {
                boolean candidateLocal = containsBeanDefinition(candidateBeanName);
                boolean primaryLocal = containsBeanDefinition(primaryBeanName);
                if (candidateLocal && primaryLocal) {
                    throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
                            "more than one 'primary' bean found among candidates: " + candidates.keySet());
                }
                else if (candidateLocal) {
                    primaryBeanName = candidateBeanName;
                }
            }
            else {
                primaryBeanName = candidateBeanName;
            }
        }
    }
    return primaryBeanName;
}

determineHighestPriorityCandidate

如果是最高级的情况

protected String determineHighestPriorityCandidate(Map candidates, Class requiredType) {
    String highestPriorityBeanName = null;
    Integer highestPriority = null;
    for (Map.Entry entry : candidates.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        if (beanInstance != null) {
            Integer candidatePriority = getPriority(beanInstance);
            if (candidatePriority != null) {
                if (highestPriorityBeanName != null) {
                    if (candidatePriority.equals(highestPriority)) {
                        throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
                                "Multiple beans found with the same priority ('" + highestPriority +
                                "') among candidates: " + candidates.keySet());
                    }
                    else if (candidatePriority < highestPriority) {
                        highestPriorityBeanName = candidateBeanName;
                        highestPriority = candidatePriority;
                    }
                }
                else {
                    highestPriorityBeanName = candidateBeanName;
                    highestPriority = candidatePriority;
                }
            }
        }
    }
    return highestPriorityBeanName;
}

isPrimary

是否为主要的,即有primary

protected boolean isPrimary(String beanName, Object beanInstance) {
    if (containsBeanDefinition(beanName)) {
        return getMergedLocalBeanDefinition(beanName).isPrimary();
    }
    BeanFactory parent = getParentBeanFactory();
    return (parent instanceof DefaultListableBeanFactory &&
            ((DefaultListableBeanFactory) parent).isPrimary(beanName, beanInstance));
}

getPriority

获取优先级

protected Integer getPriority(Object beanInstance) {
    Comparator comparator = getDependencyComparator();
    if (comparator instanceof OrderComparator) {
        return ((OrderComparator) comparator).getPriority(beanInstance);
    }
    return null;
} 
 

matchesBeanName

确定给定的候选名称是否与bean名或别名匹配存储在这个bean定义中

protected boolean matchesBeanName(String beanName, @Nullable String candidateName) {
    return (candidateName != null &&
            (candidateName.equals(beanName) || ObjectUtils.containsElement(getAliases(beanName), candidateName)));
}

isSelfReference

是否自引用

private boolean isSelfReference(@Nullable String beanName, @Nullable String candidateName) {
    return (beanName != null && candidateName != null &&
            (beanName.equals(candidateName) || (containsBeanDefinition(candidateName) &&
                    beanName.equals(getMergedLocalBeanDefinition(candidateName).getFactoryBeanName()))));
}

raiseNoMatchingBeanFound

没有匹配,抛异常

private void raiseNoMatchingBeanFound(
        Class type, ResolvableType resolvableType, DependencyDescriptor descriptor) throws BeansException {

    checkBeanNotOfRequiredType(type, descriptor);

    throw new NoSuchBeanDefinitionException(resolvableType,
            "expected at least 1 bean which qualifies as autowire candidate. " +
            "Dependency annotations: " + ObjectUtils.nullSafeToString(descriptor.getAnnotations()));
}

checkBeanNotOfRequiredType

private void checkBeanNotOfRequiredType(Class type, DependencyDescriptor descriptor) {
    
    for (String beanName : this.beanDefinitionNames) {
        RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
        Class targetType = mbd.getTargetType();
        // 指定的的类型是mbd的targetType子类且符合自动注入条件
        if (targetType != null && type.isAssignableFrom(targetType) &&
                isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) {
            // Probably a proxy interfering with target type match -> throw meaningful exception.
            Object beanInstance = getSingleton(beanName, false);
            // 获取bean的类型
            Class beanType = (beanInstance != null && beanInstance.getClass() != NullBean.class ?
                    beanInstance.getClass() : predictBeanType(beanName, mbd));
            // 实际类型不是指定类型的子类
            if (beanType != null && !type.isAssignableFrom(beanType)) {
                throw new BeanNotOfRequiredTypeException(beanName, type, beanType);
            }
        }
    }
    // 从父类检查
    BeanFactory parent = getParentBeanFactory();
    if (parent instanceof DefaultListableBeanFactory) {
        ((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor);
    }
}

createOptionalDependency

创建一个Optional的依赖

private Optional createOptionalDependency(
        DependencyDescriptor descriptor, @Nullable String beanName, final Object... args) {

    DependencyDescriptor descriptorToUse = new NestedDependencyDescriptor(descriptor) {
        @Override
        public boolean isRequired() {
            return false;
        }
        @Override
        public Object resolveCandidate(String beanName, Class requiredType, BeanFactory beanFactory) {
            return (!ObjectUtils.isEmpty(args) ? beanFactory.getBean(beanName, args) :
                    super.resolveCandidate(beanName, requiredType, beanFactory));
        }
    };
    Object result = doResolveDependency(descriptorToUse, beanName, null, null);
    return (result instanceof Optional ? (Optional) result : Optional.ofNullable(result));
}

toString

重写toString方法

public String toString() {
    StringBuilder sb = new StringBuilder(ObjectUtils.identityToString(this));
    sb.append(": defining beans [");
    sb.append(StringUtils.collectionToCommaDelimitedString(this.beanDefinitionNames));
    sb.append("]; ");
    BeanFactory parent = getParentBeanFactory();
    if (parent == null) {
        sb.append("root of factory hierarchy");
    }
    else {
        sb.append("parent: ").append(ObjectUtils.identityToString(parent));
    }
    return sb.toString();
}

你可能感兴趣的:(源码分析,spring,java)