Spring4.3.x 容器中bean的创建过程(2)——实例化Bean

概述

在Spring4.3.x 容器中bean的创建过程(1)——走进初始化bean的主要战场一篇中我们找到了初始化bean的主要场所在AbstractAutowireCapableBeanFactory类中的doCreateBean方法中,在这个方法中首先调用createBeanInstance方法创建bean的实例;然后调用populateBean方法设置bean的属性;接着调用initializeBean方法执行Bean后处理器和InitializingBean对象的afterPropertiesSet方法以及init-method方法;最后调用registerDisposableBeanIfNecessary方法注册bean的销毁方法。它的每一步都比较繁琐,所以我把他们分开来探讨,在这一篇我们只讨论第一步bean的实例化过程中会遇到哪些情况,以及如何处理各个情况。

创建对象有两种方式,其一是直接使用构造器创建对象;其二是使用工厂模式间接创建对象,这中方式又分为静态工厂、工厂方法和抽象工厂3类。在spring中,从纯XML配置的角度出发有四种方式,第一种是使用默认构造器,第二种是使用带参构造器,第三种是使用静态工厂,第四种是使用实例工厂。

    
    <bean id="studentServiceDefault" class="com.chyohn.service.StudentService">
        <property name="name" value="默认构造器"/>
    bean>

    
    <bean id="studentServiceArgs" class="com.chyohn.service.StudentService">
        <constructor-arg name="name" value="带参构造器"/>
    bean>

    
    <bean id="studentServiceStaticF" class="com.chyohn.factory.StudentServiceFactory" factory-method="createSudentService" />

    
    <bean id="studentServiceFactoryBean" class="com.chyohn.factory.StudentServiceFactory"/>
    <bean id="studentServiceSimpleF" factory-bean="studentServiceFactoryBean" factory-method="createSudentService">
        <constructor-arg name="name" value="简单工厂"/>
    bean>

Spring中不管是工厂方法还是抽象工厂,只要需要实例化工厂对象的都需要通过第四种配置方式创建bean。下面我们看看Spring如何创建这四种配置方式的bean。

实例化bean

AbstractAutowireCapableBeanFactory类中的doCreateBean方法调用它的createBeanInstance方法实例化bean并返回bean的包装器BeanWrapper对象,源码如下。

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
        // 获取bean的Class对象
        Class beanClass = resolveBeanClass(mbd, beanName);

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

        if (mbd.getFactoryMethodName() != null)  {
            // 使用指定的工厂方法创建bean示例
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }

        // 再一次创建已经创建过的bean
        boolean resolved = false;
        boolean autowireNecessary = false;
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }
        if (resolved) {
            if (autowireNecessary) {
                return autowireConstructor(beanName, mbd, null, null);
            }
            else {
                return instantiateBean(beanName, mbd);
            }
        }

        // 获取bean的构造器
        Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null ||
                mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
            // 通过带参构造器创建bean对象
            return autowireConstructor(beanName, mbd, ctors, args);
        }

        // 通过无参构造器创建bean对象
        return instantiateBean(beanName, mbd);
    }

createBeanInstance方法所做的事情非常清晰,它根据bean的定义选择bean采用何种方式创建,这个方法把bean的创建分成3种方式,其一是通过指定的工厂创建bean,这个包括使用实例工厂或静态工厂;其二是通过带参构造器创建bean;其三是通过无参构造器创建bean。下面我们分别探讨这三种方式。

1. 使用工厂创建bean

createBeanInstance方法调用AbstractAutowireCapableBeanFactory对象的instantiateUsingFactoryMethod方法通过使用工厂方法创建bean实例的入口,源码如下。

    protected BeanWrapper instantiateUsingFactoryMethod(
            String beanName, RootBeanDefinition mbd, Object[] explicitArgs) {

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

instantiateUsingFactoryMethod方法首先创建一个ConstructorResolver对象后,调用这个对象的instantiateUsingFactoryMethod方法来实例化bean。instantiateUsingFactoryMethod方法的源码如下。

    public BeanWrapper instantiateUsingFactoryMethod(
            final String beanName, final RootBeanDefinition mbd, final Object[] explicitArgs) {

        BeanWrapperImpl bw = new BeanWrapperImpl();
        // 向BeanWrapper对象中添加ConversionService对象和属性编辑器PropertyEditor对象
        this.beanFactory.initBeanWrapper(bw);

        Object factoryBean;
        Class factoryClass;
        boolean isStatic;

        String factoryBeanName = mbd.getFactoryBeanName();
        if (factoryBeanName != null) {
            if (factoryBeanName.equals(beanName)) {
                throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
                        "factory-bean reference points back to the same bean definition");
            }
            // 获取工厂实例
            factoryBean = this.beanFactory.getBean(factoryBeanName);
            if (factoryBean == null) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "factory-bean '" + factoryBeanName + "' (or a BeanPostProcessor involved) returned null");
            }
            if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {
                throw new IllegalStateException("About-to-be-created singleton instance implicitly appeared " +
                        "through the creation of the factory bean that its bean definition points to");
            }
            factoryClass = factoryBean.getClass();
            isStatic = false;
        } else {
            // 静态工厂创建bean,必须要提供工厂的全类名
            if (!mbd.hasBeanClass()) {
                throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
                        "bean definition declares neither a bean class nor a factory-bean reference");
            }
            factoryBean = null;
            factoryClass = mbd.getBeanClass();
            isStatic = true;
        }

        Method factoryMethodToUse = null;
        ArgumentsHolder argsHolderToUse = null;
        Object[] argsToUse = null;

        // 获取工厂方法的参数
        if (explicitArgs != null) {
            argsToUse = explicitArgs;
        } else {
            Object[] argsToResolve = null;
            synchronized (mbd.constructorArgumentLock) {
                factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod;
                if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) {
                    // Found a cached factory method...
                    argsToUse = mbd.resolvedConstructorArguments;
                    if (argsToUse == null) {
                        argsToResolve = mbd.preparedConstructorArguments;
                    }
                }
            }
            if (argsToResolve != null) {
                argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve);
            }
        }

        // 获取工厂方法,和工厂方法所需要的参数
        if (factoryMethodToUse == null || argsToUse == null) {
            // 工厂对象可能是一个被代理的对象,那么需要获取正确的工厂类全名称
            factoryClass = ClassUtils.getUserClass(factoryClass);

            // 获取所有待定的工厂方法
            Method[] rawCandidates = getCandidateMethods(factoryClass, mbd);
            List candidateSet = new ArrayList();
            for (Method candidate : rawCandidates) {
                if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {
                    candidateSet.add(candidate);
                }
            }
            Method[] candidates = candidateSet.toArray(new Method[candidateSet.size()]);
            AutowireUtils.sortFactoryMethods(candidates);

            ConstructorArgumentValues resolvedValues = null;
            boolean autowiring = (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
            int minTypeDiffWeight = Integer.MAX_VALUE;
            Set ambiguousFactoryMethods = null;

            int minNrOfArgs;
            if (explicitArgs != null) {
                minNrOfArgs = explicitArgs.length;
            } else {
                ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
                resolvedValues = new ConstructorArgumentValues();
                minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
            }

            LinkedList causes = null;

            for (Method candidate : candidates) {
                Class[] paramTypes = candidate.getParameterTypes();

                if (paramTypes.length >= minNrOfArgs) {
                    ArgumentsHolder argsHolder;

                    if (resolvedValues != null) {
                        try {
                            String[] paramNames = null;
                            ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                            if (pnd != null) {
                                paramNames = pnd.getParameterNames(candidate);
                            }
                            argsHolder = createArgumentArray(
                                    beanName, mbd, resolvedValues, bw, paramTypes, paramNames, candidate, autowiring);
                        } catch (UnsatisfiedDependencyException ex) {
                            if (this.beanFactory.logger.isTraceEnabled()) {
                                this.beanFactory.logger.trace("Ignoring factory method [" + candidate +
                                        "] of bean '" + beanName + "': " + ex);
                            }
                            if (causes == null) {
                                causes = new LinkedList();
                            }
                            causes.add(ex);
                            continue;
                        }
                    } else {
                        // 如果在配置的时候,参数个数必须要与方法的参数个数相同
                        if (paramTypes.length != explicitArgs.length) {
                            continue;
                        }
                        argsHolder = new ArgumentsHolder(explicitArgs);
                    }

                    int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
                            argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
                    if (typeDiffWeight < minTypeDiffWeight) {
                        // 查找到完全匹配的工厂方法
                        factoryMethodToUse = candidate;
                        argsHolderToUse = argsHolder;
                        argsToUse = argsHolder.arguments;
                        minTypeDiffWeight = typeDiffWeight;
                        ambiguousFactoryMethods = null;
                    } else if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight &&
                            !mbd.isLenientConstructorResolution() &&
                            paramTypes.length == factoryMethodToUse.getParameterTypes().length &&
                            !Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) {
                        // 查找到多个可匹配的方法
                        if (ambiguousFactoryMethods == null) {
                            ambiguousFactoryMethods = new LinkedHashSet();
                            ambiguousFactoryMethods.add(factoryMethodToUse);
                        }
                        ambiguousFactoryMethods.add(candidate);
                    }
                }
            }

            if (factoryMethodToUse == null) {
                // 没有查找到可执行的工厂方法,抛出异常
                if (causes != null) {
                    UnsatisfiedDependencyException ex = causes.removeLast();
                    for (Exception cause : causes) {
                        this.beanFactory.onSuppressedException(cause);
                    }
                    throw ex;
                }
                List argTypes = new ArrayList(minNrOfArgs);
                if (explicitArgs != null) {
                    for (Object arg : explicitArgs) {
                        argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
                    }
                } else {
                    Set valueHolders = new LinkedHashSet(resolvedValues.getArgumentCount());
                    valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values());
                    valueHolders.addAll(resolvedValues.getGenericArgumentValues());
                    for (ValueHolder value : valueHolders) {
                        String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType()) :
                                (value.getValue() != null ? value.getValue().getClass().getSimpleName() : "null"));
                        argTypes.add(argType);
                    }
                }
                String argDesc = StringUtils.collectionToCommaDelimitedString(argTypes);
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "No matching factory method found: " +
                        (mbd.getFactoryBeanName() != null ?
                            "factory bean '" + mbd.getFactoryBeanName() + "'; " : "") +
                        "factory method '" + mbd.getFactoryMethodName() + "(" + argDesc + ")'. " +
                        "Check that a method with the specified name " +
                        (minNrOfArgs > 0 ? "and arguments " : "") +
                        "exists and that it is " +
                        (isStatic ? "static" : "non-static") + ".");
            } else if (void.class == factoryMethodToUse.getReturnType()) {
                // 查找到的工厂方法的返回类型为void,抛出异常
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Invalid factory method '" + mbd.getFactoryMethodName() +
                        "': needs to have a non-void return type!");
            } else if (ambiguousFactoryMethods != null) {
                // 查找到多个匹配的工厂方法,抛出异常
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Ambiguous factory method matches found in bean '" + beanName + "' " +
                        "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
                        ambiguousFactoryMethods);
            }

            if (explicitArgs == null && argsHolderToUse != null) {
                // 没有传入参数且
                argsHolderToUse.storeCache(mbd, factoryMethodToUse);
            }
        }

        try {
            // 实例化bean
            Object beanInstance;

            if (System.getSecurityManager() != null) {
                final Object fb = factoryBean;
                final Method factoryMethod = factoryMethodToUse;
                final Object[] args = argsToUse;
                beanInstance = AccessController.doPrivileged(new PrivilegedAction() {
                    @Override
                    public Object run() {
                        // 通过执行工厂方法来创建bean示例
                        return beanFactory.getInstantiationStrategy().instantiate(
                                mbd, beanName, beanFactory, fb, factoryMethod, args);
                    }
                }, beanFactory.getAccessControlContext());
            } else {
                // 通过执行工厂方法来创建bean示例
                beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(
                        mbd, beanName, this.beanFactory, factoryBean, factoryMethodToUse, argsToUse);
            }

            if (beanInstance == null) {
                return null;
            }
            // 让BeanWraper对象保存bean实例
            bw.setBeanInstance(beanInstance);
            return bw;
        } catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Bean instantiation via factory method failed", ex);
        }
    } 
  

instantiateUsingFactoryMethod方法首先获取工厂对象,然后获取工厂方法及其参数,最后调用InstantiationStrategy对象的instantiate方法来创建bean实例。Spring bean工厂默认的InstantiationStrategy对象是CglibSubclassingInstantiationStrategy,这个instantiate方法在CglibSubclassingInstantiationStrategy的父类SimpleInstantiationStrategy中有实现,代码如下。

    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
            Object factoryBean, final Method factoryMethod, Object... args) {

        try {
            // 设置方法的访问权限为可访问
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction() {
                    @Override
                    public Object run() {
                        ReflectionUtils.makeAccessible(factoryMethod);
                        return null;
                    }
                });
            } else {
                ReflectionUtils.makeAccessible(factoryMethod);
            }

            Method priorInvokedFactoryMethod = currentlyInvokedFactoryMethod.get();
            try {
                currentlyInvokedFactoryMethod.set(factoryMethod);
                // 执行工厂方法,并返回实例
                return factoryMethod.invoke(factoryBean, args);
            } finally {
                if (priorInvokedFactoryMethod != null) {
                    currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod);
                } else {
                    currentlyInvokedFactoryMethod.remove();
                }
            }
        } catch (IllegalArgumentException ex) {
            throw new BeanInstantiationException(factoryMethod,
                    "Illegal arguments to factory method '" + factoryMethod.getName() + "'; " +
                    "args: " + StringUtils.arrayToCommaDelimitedString(args), ex);
        } catch (IllegalAccessException ex) {
            throw new BeanInstantiationException(factoryMethod,
                    "Cannot access factory method '" + factoryMethod.getName() + "'; is it public?", ex);
        } catch (InvocationTargetException ex) {
            String msg = "Factory method '" + factoryMethod.getName() + "' threw exception";
            if (bd.getFactoryBeanName() != null && owner instanceof ConfigurableBeanFactory &&
                    ((ConfigurableBeanFactory) owner).isCurrentlyInCreation(bd.getFactoryBeanName())) {
                msg = "Circular reference involving containing bean '" + bd.getFactoryBeanName() + "' - consider " +
                        "declaring the factory method as static for independence from its containing instance. " + msg;
            }
            throw new BeanInstantiationException(factoryMethod, msg, ex.getTargetException());
        }
    } 
  

instantiate方法最主要的目的,就是通过java反射执行工厂方法并返回创建好的实例。

2. 使用带参构造器创建bean

createBeanInstance方法调用AbstractAutowireCapableBeanFactory对象的autowireConstructor方法是使用带参构造器创建bean实例的入口,源码如下。

    protected BeanWrapper autowireConstructor(
            String beanName, RootBeanDefinition mbd, Constructor[] ctors, Object[] explicitArgs) {

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

autowireConstructor方法首先创建一个ConstructorResolver对象后,调用这个对象的autowireConstructor方法来实例化bean。autowireConstructor方法的源码如下。

    public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd,
            Constructor[] chosenCtors, final Object[] explicitArgs) {

        BeanWrapperImpl bw = new BeanWrapperImpl();
        // 向BeanWrapper对象中添加ConversionService对象和属性编辑器PropertyEditor对象
        this.beanFactory.initBeanWrapper(bw);

        Constructor constructorToUse = null;
        ArgumentsHolder argsHolderToUse = null;
        Object[] argsToUse = null;

        if (explicitArgs != null) {
            argsToUse = explicitArgs;
        } else {
            Object[] argsToResolve = null;
            synchronized (mbd.constructorArgumentLock) {
                constructorToUse = (Constructor) mbd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                    // 从缓存中获取构造器和参数
                    argsToUse = mbd.resolvedConstructorArguments;
                    if (argsToUse == null) {
                        argsToResolve = mbd.preparedConstructorArguments;
                    }
                }
            }
            if (argsToResolve != null) {
                argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
            }
        }

        if (constructorToUse == null) {
            // 相应的构造器不能从缓存中获取时
            // 获取正确的构造器及其参数
            boolean autowiring = (chosenCtors != null ||
                    mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
            ConstructorArgumentValues resolvedValues = null;

            int minNrOfArgs;
            if (explicitArgs != null) {
                minNrOfArgs = explicitArgs.length;
            } else {
                ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
                resolvedValues = new ConstructorArgumentValues();
                minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
            }

            Constructor[] candidates = chosenCtors;
            if (candidates == null) {
                Class beanClass = mbd.getBeanClass();
                try {
                    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);
                }
            }
            AutowireUtils.sortConstructors(candidates);
            int minTypeDiffWeight = Integer.MAX_VALUE;
            Set> ambiguousConstructors = null;
            LinkedList causes = null;

            for (Constructor candidate : candidates) {
                Class[] paramTypes = candidate.getParameterTypes();

                if (constructorToUse != null && argsToUse.length > paramTypes.length) {
                    // 找到匹配的构造器,这终止循环
                    break;
                }
                if (paramTypes.length < minNrOfArgs) {
                    // 当前循环的构造器参数个数小于要求的最小参数个数,那么不匹配,继续从匹配下一个
                    continue;
                }

                ArgumentsHolder argsHolder;
                if (resolvedValues != null) {
                    // 没有提供构造器参数时执行此段代码
                    // 这段代码的作用是获取构造器的参数,可能需要自动装配,比如@Autowire、@Value注解的参数
                    try {
                        // 从@ConstructorProperties注解中获取构造器的参数名称列表
                        String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
                        if (paramNames == null) {
                            // 通过ParameterNameDiscoverer对象获取构造器的参数名称列表
                            ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                            if (pnd != null) {
                                paramNames = pnd.getParameterNames(candidate);
                            }
                        }
                        // 获取构造器参数值列表
                        // 在这一步会先把未初始化的参数初始化
                        argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
                                getUserDeclaredConstructor(candidate), autowiring);
                    } catch (UnsatisfiedDependencyException ex) {
                        if (this.beanFactory.logger.isTraceEnabled()) {
                            this.beanFactory.logger.trace(
                                    "Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
                        }
                        if (causes == null) {
                            causes = new LinkedList();
                        }
                        causes.add(ex);
                        continue;
                    }
                } else {
                    // 当前循环的构造器参数个数必须等于提供的参数个数,否则继续查找下一个
                    if (paramTypes.length != explicitArgs.length) {
                        continue;
                    }
                    argsHolder = new ArgumentsHolder(explicitArgs);
                }

                int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
                        argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
                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.storeCache(mbd, constructorToUse);
            }
        }

        try {
            // 拿到构造器对象和其所需参数后
            // 实例化bean
            Object beanInstance;

            if (System.getSecurityManager() != null) {
                final Constructor ctorToUse = constructorToUse;
                final Object[] argumentsToUse = argsToUse;
                beanInstance = AccessController.doPrivileged(new PrivilegedAction() {
                    @Override
                    public Object run() {
                        // 通过构造器实例化bean
                        return beanFactory.getInstantiationStrategy().instantiate(
                                mbd, beanName, beanFactory, ctorToUse, argumentsToUse);
                    }
                }, beanFactory.getAccessControlContext());
            } else {
                // 通过构造器实例化bean
                beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(
                        mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
            }

            // 让BeanWraper对象保存bean实例
            bw.setBeanInstance(beanInstance);
            return bw;
        } catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Bean instantiation via constructor failed", ex);
        }
    } 
  

autowireConstructor方法首先获取构造器的参数列表对象和构造器对象,最后执行初始化策略器InstantiationStrategy对象的instantiate方法,这个方法的实现在SimpleInstantiationStrategy类中,源码如下。

    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
            final Constructor ctor, Object... args) {

        if (bd.getMethodOverrides().isEmpty()) {
            // 没有配置lookup-method或者replaced-method标签或者@Lookup注解
            if (System.getSecurityManager() != null) {
                // use own privileged to change accessibility (when security is on)
                AccessController.doPrivileged(new PrivilegedAction() {
                    @Override
                    public Object run() {
                        ReflectionUtils.makeAccessible(ctor);
                        return null;
                    }
                });
            }
            // 通过BeanUtils直接使用构造器对象实例化bean
            return BeanUtils.instantiateClass(ctor, args);
        } else {
            // 生成CGLIB创建的子类对象
            return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
        }
    } 
  

如果bean的配置没有lookup-method或者replaced-method标签或者@Lookup注解,则直接使用构造器创建bean,否则调用SimpleInstantiationStrategy类或者其子类的instantiateWithMethodInjection方法。这个方法在SimpleInstantiationStrategy类的实现如下。

    protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner,
            Constructor ctor, Object... args) {

        throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
    }

下面是CglibSubclassingInstantiationStrategy类实现的instantiateWithMethodInjection方法的源码。

    @Override
    protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner,
            Constructor ctor, Object... args) {

        // 通过CGLIB生成一个子类对象
        return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
    }

CglibSubclassCreator类是CglibSubclassingInstantiationStrategy的私有静态类,下面是它的instantiate方法源码。

        public Object instantiate(Constructor ctor, Object... args) {
            // 通过Cglib创建一个代理类
            Class subclass = createEnhancedSubclass(this.beanDefinition);
            Object instance;
            if (ctor == null) {
                // 没有提供构造器对象,通过BeanUtils工具类使用默认构造器创建一个bean实例
                instance = BeanUtils.instantiateClass(subclass);
            } else {
                try {
                    // 获取代理类对应的构造器对象,并实例化bean
                    Constructor enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
                    instance = enhancedSubclassConstructor.newInstance(args);
                } catch (Exception ex) {
                    throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
                            "Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
                }
            }
            // 为了避免memory leaks异常,直接在bean实例上设置回调对象
            Factory factory = (Factory) instance;
            factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
                    new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
                    new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
            return instance;
        }

CglibSubclassCreator类对象通过调用它的createEnhancedSubclass方法来创建一个Cglib代理的子类,源码如下。

        private Class createEnhancedSubclass(RootBeanDefinition beanDefinition) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanDefinition.getBeanClass());
            enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
            if (this.owner instanceof ConfigurableBeanFactory) {
                ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
                enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
            }
            enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
            enhancer.setCallbackTypes(CALLBACK_TYPES);
            return enhancer.createClass();
        }

3. 使用无参构造器创建bean

createBeanInstance方法调用AbstractAutowireCapableBeanFactory对象的instantiateBean方法是使用无参构造器创建bean实例的入口,源码如下。

    protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
        try {
            Object beanInstance;
            final BeanFactory parent = this;
            if (System.getSecurityManager() != null) {
                beanInstance = AccessController.doPrivileged(new PrivilegedAction() {
                    @Override
                    public Object run() {
                        return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                    }
                }, getAccessControlContext());
            } else {
                beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
            }
            // 创建BeanWrapper对象
            BeanWrapper bw = new BeanWrapperImpl(beanInstance);
            // 初始化BeanWrapper,向BeanWrapper对象中添加ConversionService对象和属性编辑器PropertyEditor对象
            initBeanWrapper(bw);
            return bw;
        } catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
        }
    } 
  

instantiateBean方法通过调用InstantiationStrategy对象的instantiateBean方法创建bean实例,这个instantiateBean方法在SimpleInstantiationStrategy类中的实现代码如下。

    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
        // Don't override the class with CGLIB if no overrides.
        if (bd.getMethodOverrides().isEmpty()) {
            // 没有配置lookup-method或者replaced-method标签或者@Lookup注解
            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(new PrivilegedExceptionAction>() {
                                @Override
                                public Constructor run() throws Exception {
                                    return clazz.getDeclaredConstructor((Class[]) null);
                                }
                            });
                        } else {
                            constructorToUse =  clazz.getDeclaredConstructor((Class[]) null);
                        }
                        // 缓存默认构造器对象
                        bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                    } catch (Throwable ex) {
                        throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                    }
                }
            }
            return BeanUtils.instantiateClass(constructorToUse);
        } else {
            // 生成CGLIB创建的子类对象
            return instantiateWithMethodInjection(bd, beanName, owner);
        }
    }

关于生成CGLIB创建的子类对象调用调用的方法和使用带参构造器实例化bean一节的一样,这里就不重复说了。

总结

(1)Spring通过实例化策略接口InstantiationStrategy的派生类创建bean,这个接口的源码如下。

public interface InstantiationStrategy {

    /**
     * 使用默认构造器创建bean实例
     * @param bd bean定义信息
     * @param beanName bean名称,可以为空
     * @param owner bean工厂
     * @return
     * @throws BeansException
     */
    Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner)
            throws BeansException;

    /**
     * 通过指定的构造器创建bean实例
     * @param bd bean定义信息
     * @param beanName bean名称,可以为空
     * @param owner bean工厂
     * @param ctor 构造器对象
     * @param args 构造器所需参数
     * @return 
     * @throws BeansException
     */
    Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
            Constructor ctor, Object... args) throws BeansException;

    /**
     * 根据指定的工厂方法创建bean实例
     * @param bd bean的定义信息
     * @param beanName bean名称,可以为空
     * @param owner bean工厂
     * @param factoryBean 工厂对象,如果为静态工厂,此参数为null
     * @param factoryMethod 工厂方法对象
     * @param args 工厂方法所需参数
     * @return 
     * @throws BeansException 
     */
    Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
            Object factoryBean, Method factoryMethod, Object... args) throws BeansException;

}

Spring默认的实例bean策略类为CglibSubclassingInstantiationStrategy。

(2)使用了lookup-method或者replaced-method标签或者@Lookup注解的bean,Spring使用Cglib的Enhancer类创建它们的代理子类。

你可能感兴趣的:(spring4源码解读)