think in spring refresh 11 - 2

创建bean实例:

// Create bean instance.

  // 如果是单例的 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> {   // 1 --------- try { return createBean(beanName, mbd, args);    // 2----------- } 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 = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); }

1  DefaultSingletonBeanRegistry中的方法:

/**
     * Return the (raw) singleton object registered under the given name,
     * creating and registering a new one if none registered yet.
     * @param beanName the name of the bean
     * @param singletonFactory the ObjectFactory to lazily create the singleton
     * with, if necessary
     * @return the registered singleton object
     */
    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(beanName, "Bean name must not be null");
        synchronized (this.singletonObjects) {
// 从一级缓存中获取, 一级缓存中存储的是创建完成的 bean,可以直接拿来使用的 Object singletonObject
= this.singletonObjects.get(beanName); if (singletonObject == null) { if (this.singletonsCurrentlyInDestruction) { throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction " + "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); } if (logger.isDebugEnabled()) { logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); }
// beforeSingletonCreation(beanName); // 1.1 ------
boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet<>(); } try {
// 这里调用的就是传入的第二个参数 用的是lambda 表达式 singletonObject
= singletonFactory.getObject(); // newSingleton = true;   // 前面为false. } catch (IllegalStateException ex) { // Has the singleton object implicitly appeared in the meantime -> // if yes, proceed with it since the exception indicates that state. singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { throw ex; } } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { for (Exception suppressedException : this.suppressedExceptions) { ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } afterSingletonCreation(beanName);  // 1.2 --------- } if (newSingleton) { // 这里为 true
// addSingleton(beanName, singletonObject); // 3 --------- } }
return singletonObject; } }

 

2  AbstractAutowireCapableBeanFactory 中的方法:

/**
     * Central method of this class: creates a bean instance,
     * populates the bean instance, applies post-processors, etc.
     * @see #doCreateBean
     */
    @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        if (logger.isTraceEnabled()) {
            logger.trace("Creating instance of bean '" + beanName + "'");
        }
        RootBeanDefinition mbdToUse = mbd;

        // Make sure bean class is actually resolved at this point, and
        // clone the bean definition in case of a dynamically resolved Class
        // which cannot be stored in the shared merged bean definition.

// Class<?> resolvedClass = resolveBeanClass(mbd, beanName); // 2.1 ------- beanClass 属性的作用是什么 ????? if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try {
// mbdToUse.prepareMethodOverrides(); }
catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.

// 实例化前的处理,给 InstantiationAwareBeanPostProcessor 一个机会返回代理对象来替代真正的 bean 实例, -----这地方还要回来看---- Object bean = resolveBeforeInstantiation(beanName, mbdToUse); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try {
/// ※※ Object beanInstance
= doCreateBean(beanName, mbdToUse, args); // 2.3 --------- if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { // A previously detected exception with proper bean creation context already, // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. throw ex; } catch (Throwable ex) { throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } }

2.1 AbstractBeanFactory 中的方法

  得到的是一个Class 类对象,不是一个 类的全名啊 ( 比如: com.xixi.Test )

protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, 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);    // 2.1.1 ------
            }
        }
        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);
        }
    }

2.1.1

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) {
            Object evaluated = evaluateBeanDefinitionString(className, mbd);
            if (!className.equals(evaluated)) {
                // A dynamically resolved expression, supported as of 4.2...
                if (evaluated instanceof Class) {
                    return (Class<?>) evaluated;
                }
                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...
        return mbd.resolveBeanClass(beanClassLoader);
    }

2.3   AbstractAutowireCapableBeanFactory 中的方法: 

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.


// Bean 包装类 BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);  // 2.3.1 ------ } if (instanceWrapper == null) {
// 核心 ------ 根据 beanName 和 RootBeanDefinition 来创建对象, args 参数传入的是 null instanceWrapper
= createBeanInstance(beanName, mbd, args); // 2.3.2 ----- }
// 拿到创建好的 bean实例 Object bean
= instanceWrapper.getWrappedInstance();
// 获取 bean 实例的类型 Class
<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType;  // 设置 mbd的解析后的目标类型 } // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try {
// 应用 MergedBeanDefinitionPostProcessor ,允许修改 MergedBeanDefinition , 修改它干什么用?? bean 都已经创建出来了!! applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); // 2.3.3 }
catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware.

// 判断是否需要提前曝光实例: 单例 && 允许循环依赖 && 当前bean正在创建中 ( 前面将这个beanName加入到了存储正在创建的beanName的set集合中) boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); }
// 添加到三级缓存 添加的是一个 ObjectFactory 对象 addSingletonFactory(beanName, ()
-> getEarlyBeanReference(beanName, mbd, bean)); // 2.3.4 } // Initialize the bean instance.


// 初始化 bean实例 Object exposedObject = bean; try {
// 对 bean 的属性进行填充,这里面可能会依赖其它的bean populateBean(beanName, mbd, instanceWrapper); // 见 think in spring refresh 11 -3
// 对bean进行初始化 exposedObject
= initializeBean(beanName, exposedObject, mbd); // 见 think in spring refresh 11 - 3 } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { // 如果允许提前曝光 只要 mbd为单例,这里应该就是 true
// 由于第二个参数为false, 所以只会在一级缓存和二级缓存中进行查找 Object earlySingletonReference
= getSingleton(beanName, false);
// 只有当前 bean 存在循环引用的时候才会为不会空 (准确说,应该是在二级缓存中,找到了一个对象,但是不一定和这个bean是同一个,涉及到代理对象)
if (earlySingletonReference != null) {
// exposedObject对象在上面经过了 initializeBean 方法, initializeBean方法还会改变 bean对象呢????
if (exposedObject == bean) {
// exposedObject
= earlySingletonReference; }
// 如果 exposedObject在initializeBean中被增强,也就是bean发生了变化, && 不允许在循环引用的情况下使用注入原始bean实例 && 当前bean被其它的bean依赖
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// 获取到依赖当前bean的所有bean的 beanName String[] dependentBeans
= getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) {
// 尝试移除这些 bean的实例,因为这些bean依赖的bean已经被增强了,它们依赖的相当于是脏数据
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
// 移除失败的,添加到下面的set 集合中。 actualDependentBeans.add(dependentBean); } }
// 如果有移除失败的 抛出异常
if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try {
// 注册用于销毁的 bean,
// 执行销毁操作的方式有三种:
 // 1) 自定义 destroy 方法 2)DisposableBean 接口 3) DestructionAwareBeanPostProcessor registerDisposableBeanIfNecessary(beanName, bean, mbd); }
catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } // 完成创建并返回 return exposedObject; }

2.3.1  AbstractAutowireCapableBeanFactory 中的 一个map 变量 

/** Cache of unfinished FactoryBean instances: FactoryBean name to BeanWrapper. */

// 存储这个有什么用呢 ??? 什么时候存储的?? 什么时候用到?? private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>();

2.3.2  AbstractAutowireCapableBeanFactory 中的 createBeanInstance 方法:

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        // Make sure bean class is actually resolved at this point.

// 解析 bean的类型信息 前面也有用到过 Class<?> beanClass = resolveBeanClass(mbd, beanName); // Modifier 是 jdk的 反射包下面的一个类,好好看一下这个类的作用 ---- 需要看----- if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } // ???? Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); } // 如果存在工厂方法,则用工厂方法实例化bean --- &&&&----- if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); } // Shortcut when re-creating the same bean...
// resolved: 构造函数或工厂方法是都已经解析过 boolean resolved = false;
// autowireNecessary : 是否需要自动注入 ( 即是否需要解析构造函数参数 ) 作用是什么??? <<<<
boolean autowireNecessary = false;
// 这里的 args 就是 null
if (args == null) { synchronized (mbd.constructorArgumentLock) { if (mbd.resolvedConstructorOrFactoryMethod != null) {
// 如果 上面那个变量不为null, 设置为 解析过 上面那个变量什么时候进行修改???? resolved
= true;
// 根据 constructorArgumentsResolved 判断是否需要自动注入 autowireNecessary
= mbd.constructorArgumentsResolved; } } } if (resolved) { if (autowireNecessary) {
// 如果已经解析过,并且需要自动注入, 执行构造函数自动注入
return autowireConstructor(beanName, mbd, null, null); // 5 ---- } else {
// 使用默认的构造函数进行 bean的实例化
return instantiateBean(beanName, mbd); } } // Candidate constructors for autowiring?
// 拿到 bean 的候选构造函数 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); // 6 if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { return autowireConstructor(beanName, mbd, ctors, args); } // Preferred constructors for default construction? ctors = mbd.getPreferredConstructors(); if (ctors != null) { return autowireConstructor(beanName, mbd, ctors, null); } // No special handling: simply use no-arg constructor.

// 使用默认的构造函数进行bean的实例化 return instantiateBean(beanName, mbd); // 9 }

2.3.3  AbstractAutowireCapableBeanFactory 中的 方法:

    protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }

2.3.4  DefaultSingletonBeanRegistry 中的方法  .   将创建的bean加入到三级缓存中,这里添加的不是bean本身,而是 bean的对象工厂, ObjectFactory. 

       仅仅是创建了bean实例,还没有对bean的属性赋值。

  protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(singletonFactory, "Singleton factory must not be null");
        synchronized (this.singletonObjects) {
            if (!this.singletonObjects.containsKey(beanName)) {    // 一级缓存中不存在当前bean
                this.singletonFactories.put(beanName, singletonFactory);  // 添加到三级缓存中
                this.earlySingletonObjects.remove(beanName);  // 从二级缓存中移除
                this.registeredSingletons.add(beanName);  // 
              }
        }
    }

  通过lambda表达式,传入的方法,作为 ObjectFactory中的 getObject方法的实现。

    protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
        Object exposedObject = bean;
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 又是用到 这种后置处理器
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
// 得到的不一定是bean了, 可能是代理对象 !!!! exposedObject
= ibp.getEarlyBeanReference(exposedObject, beanName); } } } return exposedObject; }

 

3 DefaultSingletonBeanRegistry 中的方法。 将新创建的 bean 加入到一级缓存中。

    protected void addSingleton(String beanName, Object singletonObject) {
        synchronized (this.singletonObjects) {
            this.singletonObjects.put(beanName, singletonObject);  // 加入到一级缓存 
            this.singletonFactories.remove(beanName);  // 从三级缓存中移除
            this.earlySingletonObjects.remove(beanName);   // 从二级缓存中移除
            this.registeredSingletons.add(beanName);   // 添加到已注册的单例的set集合中   哪里会用到 ????
        }
    }

 

5

  protected BeanWrapper autowireConstructor(
            String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {

        return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
    }

ConstructorResolver 中的方法:     【 要创建对象,那么就一定要用到构造函数  <<<<】

  public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
            @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
// bean 包装类    作用是什么 ?? 为什么要有这个类 ???
        BeanWrapperImpl bw = new BeanWrapperImpl();
        this.beanFactory.initBeanWrapper(bw);
// 最终用于实例化的构造函数
        Constructor<?> constructorToUse = null;
        ArgumentsHolder argsHolderToUse = null;
        Object[] argsToUse = null;
// 如果 explicitArgs 不为空,则构造函数的参数直接使用 explicitArgs. 通过getBean 方法调用时,指定了args的参数,这里就不为 null
if (explicitArgs != null) { argsToUse = explicitArgs; } else { Object[] argsToResolve = null; synchronized (mbd.constructorArgumentLock) {
// Constructor 是反射包下面的类 ------ &&&& ----- constructorToUse
= (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
// 如果实例化bean用到的构造函数不为null, 并且 RootBeanDefinition 中已经有了解析后的构造函数的参数 怎么解析的???
if (constructorToUse != null && mbd.constructorArgumentsResolved) { // Found a cached constructor...

// 因为上面确定了构造函数的参数已经被解析过了 这里从缓存中获取构造函数参数 argsToUse = mbd.resolvedConstructorArguments; if (argsToUse == null) {
// 当 构造函数的参数被解析过了之后, 也就是 constructorArgumentResolved 为 true 后, resolvedConstructorArguments和
// preparedConstructorArguments 中 就 必然有一个缓存了构造函数的参数 argsToResolve
= mbd.preparedConstructorArguments; } } }
// 这个和上面的几个 if 搭配的就很 妙
if (argsToResolve != null) {
// 如果 argsToResolve 为空,则对构造函数的参数进行进一步的解析
// 例如 构造函数为 A(int,int), 通过这种方法后就会把配置中的 (”1“,”1“)转换为 (1,1) argsToUse
= resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true); } } if (constructorToUse == null || argsToUse == null) { // Take specified constructors, if any. Constructor<?>[] candidates = chosenCtors; if (candidates == null) { // 如果传入的构造函数为null
// 获取 bean的类型 例如 com.xixi.Test Class
<?> beanClass = mbd.getBeanClass(); try {
// 是否允许访问非public的构造函数和方法 ? 所有声明的构造函数 : public 型的构造函数 candidates
= (mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors()); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex); } } // if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) { Constructor<?> uniqueCandidate = candidates[0]; if (uniqueCandidate.getParameterCount() == 0) { synchronized (mbd.constructorArgumentLock) { mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate; mbd.constructorArgumentsResolved = true; mbd.resolvedConstructorArguments = EMPTY_ARGS; } bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS)); return bw; } } // Need to resolve the constructor.

boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR); ConstructorArgumentValues resolvedValues = null; // 构造函数中参数个数 (还没有明确是哪个构造函数吧) int minNrOfArgs; if (explicitArgs != null) { // getBean中传来的args参数 通常为 null 吧 minNrOfArgs = explicitArgs.length; } else { ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); resolvedValues = new ConstructorArgumentValues();
// ----- minNrOfArgs
= resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
// 这边解析 mbd中的构造函数参数值,主要是处理我们通过 xml方式定义的构造函数注入的参数
// 如果是通过 @Autowire 注解直接修饰构造函数,那么 mbd 是没有这些参数值的 } // 对候选的构造函数排序 public的构造函数排前面; 参数多的构造函数排前面 AutowireUtils.sortConstructors(candidates);
int minTypeDiffWeight = Integer.MAX_VALUE; Set<Constructor<?>> ambiguousConstructors = null; LinkedList<UnsatisfiedDependencyException> causes = null; for (Constructor<?> candidate : candidates) { int parameterCount = candidate.getParameterCount(); // 如果已经找到目标构造函数 (怎么找到的???) 并且目标构造函数需要的参数个数大于 当前遍历的构造函数的参数个数 跳出循环,因为后面的也都不合适 if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) { // Already found greedy constructor that can be satisfied -> // do not look any further, there are only less greedy constructors left. break; } if (parameterCount < minNrOfArgs) { continue; } ArgumentsHolder argsHolder; Class<?>[] paramTypes = candidate.getParameterTypes(); if (resolvedValues != null) { try {
// 解析使用 ConstructorProperties 注解的构造函数参数 String[] paramNames
= ConstructorPropertiesChecker.evaluate(candidate, parameterCount); if (paramNames == null) {
// 获取参数名称解析器 ParameterNameDiscoverer pnd
= this.beanFactory.getParameterNameDiscoverer(); if (pnd != null) {
// 获得构造函数的参数名称 --- 如何获得的??? paramNames
= pnd.getParameterNames(candidate); } } argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1); } catch (UnsatisfiedDependencyException ex) { if (logger.isTraceEnabled()) { logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex); } // Swallow and try next constructor. if (causes == null) { causes = new LinkedList<>(); } causes.add(ex); continue; } } else { // Explicit arguments given -> arguments length must match exactly. if (parameterCount != explicitArgs.length) { continue; } argsHolder = new ArgumentsHolder(explicitArgs); } int typeDiffWeight = (mbd.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes)); // Choose this constructor if it represents the closest match. if (typeDiffWeight < minTypeDiffWeight) { constructorToUse = candidate; argsHolderToUse = argsHolder; argsToUse = argsHolder.arguments; minTypeDiffWeight = typeDiffWeight; ambiguousConstructors = null; } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) { if (ambiguousConstructors == null) { ambiguousConstructors = new LinkedHashSet<>(); ambiguousConstructors.add(constructorToUse); } ambiguousConstructors.add(candidate); } } if (constructorToUse == null) { if (causes != null) { UnsatisfiedDependencyException ex = causes.removeLast(); for (Exception cause : causes) { this.beanFactory.onSuppressedException(cause); } throw ex; } throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)"); } else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Ambiguous constructor matches found in bean '" + beanName + "' " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors); } if (explicitArgs == null && argsHolderToUse != null) { argsHolderToUse.storeCache(mbd, constructorToUse); } } Assert.state(argsToUse != null, "Unresolved constructor arguments"); bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse)); return bw; }

 

6   AbstractAutowireCapableBeanFactory  中的方法: 找到用于bean实例化的构造函数

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
            throws BeansException {

        if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                    SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
// 例如, 如果采用 @Autowire 注解修饰构造函数,则构造函数会在这里被 AutowiredAnnotationBeanPostProcessor 找到 Constructor
<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); if (ctors != null) { return ctors; } } } } return null; }

这个接口就这三个方法: 在bean的实例化过程中都有涉及到。

 

 

 

9 默认的构造函数进行 bean 的实例化

  protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
        try {
            Object beanInstance;
            if (System.getSecurityManager() != null) {
                beanInstance = AccessController.doPrivileged(
                        (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
                        getAccessControlContext());
            }
            else {
// 获取实例化策略 ,调用它的实例化方法 beanInstance
= getInstantiationStrategy().instantiate(mbd, beanName, this); // 9.1 } BeanWrapper bw = new BeanWrapperImpl(beanInstance); initBeanWrapper(bw); return bw; } catch (Throwable ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); } }

9.1  实例化策略

/** Strategy for creating bean instances. */
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

  实例化方法:

public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        // Don't override the class with CGLIB if no overrides.
        if (!bd.hasMethodOverrides()) {
            Constructor<?> constructorToUse;
            synchronized (bd.constructorArgumentLock) {
                constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse == null) {
                    final Class<?> clazz = bd.getBeanClass();
                    if (clazz.isInterface()) {
                        throw new BeanInstantiationException(clazz, "Specified class is an interface");
                    }
                    try {
                        if (System.getSecurityManager() != null) {
                            constructorToUse = AccessController.doPrivileged(
                                    (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                        }
                        else {
                            constructorToUse = clazz.getDeclaredConstructor();
                        }
                        bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                    }
                    catch (Throwable ex) {
                        throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                    }
                }
            }
            return BeanUtils.instantiateClass(constructorToUse);
        }
        else {
            // Must generate CGLIB subclass.
            return instantiateWithMethodInjection(bd, beanName, owner);
        }
    }

 

posted @ 2020-12-02 20:11  你眼里的星辰  阅读(81)  评论(0)    收藏  举报