概述

  这个方法我们并不陌生,通常我们在程序中都会先获取到ApplicationContext,之后调用getBean()方法获取bean,那这个方法是如何获取的bean呢?下面就来分析一下

 

getBean()方法

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

doGetBean()方法

  这里我先说一下这个方法的调用流程

  1. 转换beanName的名称,因为Bean和FactoryBean不同,获取bean的方法不同,如果要想获取FactoryBean,需要在beanName前面加上&符号
  2. 从singletonObjects中获取,实例化好的bean都会放到这个容器中
  3. 如果singletonObjects不存在,就从bean的父bean中寻找
  4. 如果父bean中也不存,就要执行创建过程了,第一步合并beanDefiniton(因为bean可能继承了很多的父类,把所有的属性合并,以字类的属性优先)
  5. 判断bean有没有依赖的bean,如果有,先创建依赖的bean
  6. 判断bean是单例模式还是原型模式,还是以上两者都不是,不同的模式采用不同的创建方法
  7. 创建完成
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
        //1. 如果name不是以&开头,直接返回name,如果是以&开头,去掉&,有多少去掉多少,之后返回,并且把name,和去掉&之后的name作为key-value存入一个
        //缓存map中
        //2. 转换别名,获得bean的真名
        final String beanName = transformedBeanName(name);
        Object bean;

        // Eagerly check singleton cache for manually registered singletons.//如果拿到单例bean直接返回
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isTraceEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            // 为什么要调用 getObjectForBeanInstance 方法,判断当前Bean是不是FactoryBean,如果是,那么要调用getObject方法
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }
        //如果bean没有创建,从父容器查找beanName对应的bean,如果存在就直接返回
        else {
            // Fail if we're already creating this bean instance:
            // We're assumably within a circular reference.
            //这里使用了一个threadlocal包裹这个一个对象,用来处理循环依赖,后面看一下这个是怎么解决循环依赖的
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            //这里的parentBeanFactory是在初始化的时候赋值的,但是这个初始化的过程中调用的是无参构造函数,并没有
            //赋值,还有一个地方就是setParentBeanFactory,这个也可以赋值,但是没有找到是在哪里调用的
            BeanFactory parentBeanFactory = getParentBeanFactory();
            //判断当前类的父类是否为空和在之前从xml中加载bean的时候有没有把这个name放入到ioc的那个map中
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    //parentBeanFactory就是父容器,从父容器中获取
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else if (requiredType != null) {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }

            if (!typeCheckOnly) {
                //将当前的name放入alreadyCreated这个map中
                markBeanAsCreated(beanName);
            }

            try {
                //这一步返回的实际上是MergeBeadDefinition,什么意思呢,就是一个bean可以设置parent属性,
                //但是这个parent并不是常说的继承来的parent,而是在定义bean的时候可以设置,那下面的方法其实就是
                //把父类中的一些属性赋值给字类,如果字类中也存在该属性的值,优先使用字类的,如果字类不存在就是使用父类的
                //这里科普个关于BeanDefinition的例子,这个就是AbstractBeanDefinition,这个是所有具体实现的beanDefinition
                //的抽象父类,然后有几个具体实现的字类RootBeanDefinition,GenericBeanDefinition,ChildBeanDefinition,有这三个
                //实现类,其中第一个不能拥有parent

                //如果父容器中不存在,就合并beanDefinition
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                //判断mbd是不是抽象的
                checkMergedBeanDefinition(mbd, beanName, args);

                // Guarantee initialization of beans that the current bean depends on.
                //这个可能来自于上面根据beanName得到的那个mbd
                //检查是否有依赖的bean,如果有,先实例化依赖的bean
                String[] dependsOn = mbd.getDependsOn();
                //当前来看,我的例子这个为null
                //如果有依赖的bean,解决循环依赖的问题
                if (dependsOn != null) {
                    //通过for循环把依赖的map全部是实例化放入到容器中
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                        }
                        //将依赖的map放入依赖map中
                        registerDependentBean(dep, beanName);
                        try {
                            //在这里获取依赖的bean,如果这里存在循环依赖就会有问题
                            getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                        }
                    }
                }

                // Create bean instance.
                if (mbd.isSingleton()) {
                    //有了beanDefinition,创建bean,这个getSingleton其实就是调用了ObjectFactory中的getObject方法
                    //这里最重要的是才createBean方法
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    //这里是说看一下上面创建的那个shareInstance是是一个什么类型的bean,如果是factoryBean之类的需要调用
                    //一下getObject()获取真正的bean
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }
                //创建prototype类型的bean
                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }
                //创建其他类型的bean
                else {
                    String scopeName = mbd.getScope();
                    if (!StringUtils.hasLength(scopeName)) {
                        throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
                    }
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                                afterPrototypeCreation(beanName);
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        throw new ScopeNotActiveException(beanName, scopeName, ex);
                    }
                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

以上方法调用的子方法很多,我分析一下createBean(),剩下的一些子方法大家自己看一下

createBean()方法

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

        if (logger.isTraceEnabled()) {
            logger.trace("Creating instance of bean '" + beanName + "'");
        }
        //这里的mbd就是合并之后的beanDefinition,这里搞了一个副本,之后的操作都是基于副本的
        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.
        //1.解析beanName对应的bean类型,比如com.test.IOCServiceImpl
        Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
        // 如果resolvedClass存在,并且mdb的beanClass类型不是Class,并且mdb的beanClass不为空(则代表beanClass存的是Class的name),

        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            // 则使用mdb深拷贝一个新的RootBeanDefinition副本,并且将解析的Class赋值给拷贝的RootBeanDefinition副本的beanClass属性,
            // 该拷贝副本取代mdb用于后续的操作
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        // Prepare method overrides.
        try {

            // 2.验证及准备覆盖的方法(对override属性进行标记及验证)
            //这里就是为了解决xml中配置的什么lookup-method,这里做的操作就是对于存在override的bean做一个标记
            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.
            // 3.实例化前的处理,给InstantiationAwareBeanPostProcessor一个机会返回代理对象来替代真正的bean实例,达到“短路”效果
            //这个就是aop操作的,在切面前编程
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {

                // 4.如果bean不为空,则会跳过Spring默认的实例化过程,
                return bean;
            }
        }
        catch (Throwable ex) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                    "BeanPostProcessor before instantiation of bean failed", ex);
        }

        try {
            // 5.创建Bean实例(真正创建Bean的方法)
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            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);
        }
    }

这个里面有两个比较重要的方法

resolveBeforeInstantiation(beanName, mbdToUse);
doCreateBean(beanName, mbdToUse, args);

第一个方法和aop有关,下篇文章在分析,下面分析一下第二个方法

   这个方法处理流程

  • 实例化bean,但是这个bean是没有属性的
  • 填充属性
  • 解决循环依赖
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            //从这个缓存中移除并获取
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            //创建bean,有三种方式
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        //这里的bean是没有填充属性的,是一个空的bean
        final Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        // Allow post-processors to modify the merged bean definition.
        // 这里又遇到后置处理了,此处的后置处理是用于处理已“合并的 BeanDefinition”
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                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.
        /**
         * earlySingletonExposure 是一个重要的变量,这里要说明一下。该变量用于表示是否提前暴露
         * 单例 bean,用于解决循环依赖。earlySingletonExposure 由三个条件综合而成,如下:
         *   条件1:mbd.isSingleton() - 表示 bean 是否是单例类型
         *   条件2:allowCircularReferences - 是否允许循环依赖
         *   条件3:isSingletonCurrentlyInCreation(beanName) - 当前 bean 是否处于创建的状态中
         *
         * earlySingletonExposure = 条件1 && 条件2 && 条件3
         *                        = 单例 && 是否允许循环依赖 && 是否存于创建状态中。
         */
        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");
            }
            // 添加工厂对象到 singletonFactories 缓存中,在第一步中getSingleton,有从这个缓存singletonFactories获取
            //工厂,之后创建bean
            addSingletonFactory(beanName,
                    // 获取早期 bean 的引用,如果 bean 中的方法被 AOP 切点所匹配到,此时 AOP 相关逻辑会介入
                    () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
            // 向 bean 实例中填充属性,populateBean 方法也是一个很重要的方法,后面会专门写文章分析
            populateBean(beanName, mbd, instanceWrapper);
            /*
             * 进行余下的初始化工作,详细如下:
             * 1. 判断 bean 是否实现了 BeanNameAware、BeanFactoryAware、
             *    BeanClassLoaderAware 等接口,并执行接口方法
             * 2. 应用 bean 初始化前置操作
             * 3. 如果 bean 实现了 InitializingBean 接口,则执行 afterPropertiesSet
             *    方法。如果用户配置了 init-method,则调用相关方法执行自定义初始化逻辑
             * 4. 应用 bean 初始化后置操作
             *
             * 另外,AOP 相关逻辑也会在该方法中织入切面逻辑,此时的 exposedObject 就变成了
             * 一个代理对象了
             */
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        }
        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) {
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                }
                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                    for (String dependentBean : dependentBeans) {
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            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
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }

        return exposedObject;
    }

进入createBeanInstance()方法

/**  在上面分注释中,factory method, constructor autowiring, or simple instantiation,这个写的很清楚
     *  就是可以采用三种方式实例化一个bean
     * 创建 bean 实例,并将实例包裹在 BeanWrapper 实现类对象中返回。createBeanInstance
     * 中包含三种创建 bean 实例的方式:
     *   1. 通过工厂方法创建 bean 实例
     *   2. 通过构造方法自动注入(autowire by constructor)的方式创建 bean 实例
     *   3. 通过无参构造方法方法创建 bean 实例
     *
     * 若 bean 的配置信息中配置了 lookup-method 和 replace-method,则会使用 CGLIB
     * 增强 bean 实例。关于这个方法,后面会专门写一篇文章介绍,这里先说这么多。
     */
    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        // Make sure bean class is actually resolved at this point.
        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());
        }
        /*
         * 当多次构建同一个 bean 时,可以使用此处的快捷路径,即无需再次推断应该使用哪种方式构造实例,
         * 以提高效率。比如在多次构建同一个 prototype 类型的 bean 时,就可以走此处的捷径。
         * 这里的 resolved 和 mbd.constructorArgumentsResolved 将会在 bean 第一次实例
         * 化的过程中被设置,在后面的源码中会分析到,先继续往下看。
         */
        //RootBeanDefinition,在这个玩意中有一个构造方法给这个玩意赋值,之后就可以使用这个函数式接口实例化
        Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) {
            return obtainFromSupplier(instanceSupplier, beanName);
        }
        //这里使用的是工厂方法创建
        if (mbd.getFactoryMethodName() != null) {
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }

        // Shortcut when re-creating the same bean...
        boolean resolved = false;
        boolean autowireNecessary = false;
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }
        //这里使用的是自动注入构造方法创建bean
        if (resolved) {
            // 通过“构造方法自动注入”的方式构造 bean 对象
            if (autowireNecessary) {
                return autowireConstructor(beanName, mbd, null, null);
            }
            else {
                // 通过“默认构造方法”的方式构造 bean 对象
                return instantiateBean(beanName, mbd);
            }
        }

        // Candidate constructors for autowiring?
        Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
            //bean初始化
            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);
    }

 

总结

  总的来说创建bean的过程代码写的很清晰,逻辑的过程页很容易明白,这里其实有两个问题没有解决,一个就是在创建单例模式的bean的时候,循环依赖是如何解决的,第二个问题就是aop在这个里面是如何织入的,之后会写文章分析上面的两个问题