• spring源码之bean加载(bean解析下篇)


    bean的加载步骤:

    MyTestBean bean = (MyTestBean) bf.getBean("myTestBean");
    步骤:
    (1) 转换对应的beanName
     name="&aa"=>name="aa" || A->B->C=>C
    (2) 尝试从缓存中加载单例
     singletonFactories集合缓存ObjectFactory
    (3) bean的实例化
     getObjectForBeanInstance(sharedInstance, name, beanName, mbd)
    (4) 原型模式的依赖检查
     A有B属性,B有A属性,属性循环依赖
     isPrototypeCurrentlyInCreation(beanName)
    (5) 检测parentBeanFactory
    (6) 将存储XML配置文件的GernericBeanDefinition转换为RootBeanDefinition
    (7) 寻找依赖
    (8) 针对不同的scope进行bean的创建
     scope="singleton||prototype||other"
    (9) 类型转换
     return (T) bean;
    代码实现如下:

    (1) 转换对应的beanName
    String beanName = transformedBeanName(name);
    (2) 尝试从缓存中加载单例
    T doGetBean(args ...){
        Object bean; 
        sharedInstance = getSingleton(beanName);
        (3) bean的实例化
        if (!sharedInstance) { // 非单例
            bean = getObjectForBeanInstance(beanName, mbd, args);
        } else { // 单例
            (4) 原型模式的依赖检查
            if (isPrototypeCurrentlyInCreation(beanName)) throw e;
            
            (5) 检测parentBeanFactory
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null) {
                nameToLoopup = orginalBeanName(name);
                // 递归到BeanFactory中寻找
                return parentBeanFactory.getBean(nameToLoopup, args);
            }
            
            (6) 将存储XML配置文件的GernericBeanDefinition转换为RootBeanDefinition
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);
            
            (7) 寻找依赖
            // 存在依赖,递归实例化bean
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dependsOnBean : dependsOn){
                    getBean(dependsOnBean);
                    registerDependentBean(dependsOnBean);
                }
            }
            
            (8) 针对不同的scope进行bean的创建
            // 实例化mbd本身
            if (mbd.isSingleton()){
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>(){
                        getObject() {
                            try {
                                return createBean(beanName, mbd, args);
                            } catch(e) {
                                destoryName(beanName);
                                throw e;
                            }
                        }
                    });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            } else if (mbd.isPrototype()) {
                prototypeInstance;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                } finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            } else {
                // 指定的scope上实例化bean
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                scopeInstance = scope.get(beanName, new ObjectFactory<Object>() {
                    getObject() {
                        try {
                            return createBean(beanName, mbd, args);
                        } finally {
                            afterPrototypeCreation(beanName);
                        }
                    }
                });
                bean = getObjectForBeanInstance(scopeInstance, name, beanName, mbd);
            }
        }
        (9) 类型转换
        if (requriedType != null) {
            return getTypeConverter().convertIfNecessary(bean, requiredType);
        }
        return (T) bean;
    }

    1. FactoryBean接口类

    FactoryBean
        |-- T getObject(); // 
        |-- Class<?> getObjectType();
        |-- boolean isSingleton();
    CarFactoryBean implements FactoryBean<Car> {
        Car getObject() {
            Car car = new Car();
            String[] infos = carInfo.split(",");
            car.setBrand(infos[0]);
            car.setMaxSpeed(Integer.valueOf(infos[1]));
            car.setPrice(Double.valueOf(infos[2]));
            return car;
        }
        
        String carInfo;
        // setter、getter方法
        isSingleton() {
            return false;
        }
    }
    <!-- srping-bean.xml -->
    <bean id="car" class="com.test.CarFactoryBean" carInfo="跑车,400,2000"/>
    代码实现:
        getBean("car") -> spring发现CarFactoryBean implements FactoryBean接口,容器调用接口方法CarFactoryBean#getObject()返回
        getBean("&car") -> CarFactoryBean
    View Code

    2. 缓存中获取单例

    Object getSingleton(String beanName) {
        return getSingleton(beanName, true);
    }
    Object getSingleton(beanName, allowEarlyReference) {
        // 检查缓存是否存在
        Object singletonObject = this.singletonObjects.get(beanName);
        if (null == getSingleton) {
            synchronized(this.singletonObjects) {
                singletonObject = this.earlySingletonObjects.get(beanName);
                if (singletonObject == null && allowEarlyReference) {
                    // 当某些方法需要提前初始化的时候会调用addSingletonFactory方法将对应的ObjectFactory初始化策略存储在singletongFactories
                    ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) {
                        // 调用预先设定的getObject方法
                        singletonObject = singletonFactory.getObject();
                        // 记录在缓存中,earlySingletonObjects与singletonFactories互斥
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject != NULL_OBJECT ? singletonObject : null;
    }
    View Code

    3. 从bean的实例中获取对象

    (1) 对FactoryBean做正确性的验证
    (2) 对非FactoryBean不做任务处理
    (3) 对bean进行转换
    (4) 将从Factory中解析bean的工作委托给getObjectFromFactoryBean
    
    getObjectForBeanInstance(beanInstance, name, beanName, mbd) {
        // &testBeanFactory
        if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
            throw e;
        }
        // &testBeanFactory
        if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
            return beanInstance;
        }
        // 加载factoryBean
        Object object = null;
        if (mbd == null) {
            // 尝试从缓存中加载bean
            object = getCachedObjectForFactoryBean(beanName);
        }
        if (object == null) {
            FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
            if (mbd == null && containsBeanDefinition(beanName)) {
                mbd = getMergedLocalBeanDefinition(beanName);
            }
            // 是否是用户定义的而不是应用程序本身定义的
            boolean synthetic = (mbd != null && mbd.isSynthetic());
            object = getObjectFromFactoryBean(factory, beanName, !synthetic);
        }
    }
    getObjectFromFactoryBean(factory, beanName, shouldPostProcess) {
        // 如果是单例
        if (factory.isSingleton() && containsSingleton(beanName)) {
            synchronized(getSingletonMutex()) {
                Object object = this.factoryBeanObjectCache.get(beanName);
                if (object == null) {
                    object = doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess);
                    this.factoryBeanObjectCache.put(beanName, object);
                }
                return object;
            }
        } else {
            return doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess);
        }
    }
    doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess) {
        Object object = null;
        try {
            if (System.getSecurityManager() != null) { // 权限验证
                try {
                    Object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){
                        run() {
                            return factory.getObject();
                        }
                    });
                } catch (e) {
                    throw e;
                }
            } else {
                object = factory.getObject();
            }
        } catch (e) {
            throw e;
        }
        if (object != null && shouldPostProcess) {
            try {
                object = postProcessObjectFromFactoryBean(object, beanName);
            } catch (e) {
                throw e;
            }
        }
        return object;
    }
    postProcessObjectFromFactoryBean(object, beanName) {
        return applyBeanPostProcessorsAfterInitialization(object, beanName);
    }
    applyBeanPostProcessorsAfterInitialization(existingBean, beanName) {
        Object result = existingBean;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            result = beanPostProcessor.postProcessorsAfterInitialization(result, beanName);
            return result;
        }
        return result;
    }
    View Code

    4. 获取单例

    (1) 检查缓存是否已经加载过
    (2) 若没有加载,则记录beanName的正在加载状态
    (3) 加载单例前记录加载状态
    (4) 通过调用参数传入的ObjectFactory的个体Object实例化bean
    (5) 加载单例后的处理方法调用
    (6) 将结果记录到缴存并删除加载bean过程中所记录的各种辅助状态
    (7) 返回处理结果
    getSingleton(beanName, new ObjectFactory) {
        synchronized (this.singletonObjects) {
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                beforeSingletonCreation(beanName);
                try {
                    singletonObject = singletonFactory.getObject();
                } catch (e) {
                    throw e;
                } finally {
                    afterSingletonCreation(beanName);
                }
                // 加入缓存
                addSingleton(beanName, singletonObject);
            }
        }
        return (singletonObject != NULL_OBJECT ? singletonObject : null)
    }
    beforeSingletonCreation(beanName) {
        if (!this.singletonsCurrentlyCreation.add(beanName)) { // 将当前正要创建的bean记录在缓存中,这样便可以对循环依赖进行检测
            throw e;
        }
    }
    afterSingletonCreation(beanName) {
        if (!this.singletonsCurrentlyCreation.remove(beanName)) { // 加载结束后,移除缓存中对该bean正在加载状态的记录
            throw e;
        }
    }
    addSingleton(beanName, singletonObject) {
        synchronized (this.singletonObjects) {
            // 将结果记录到缓存,并删除加载bean过程中所记录的辅助状态
            this.singletonObjects.put(beanName, singletonObject);
            this.singletonFatories.remove(beanName);
            this.earlySingletonObjects.remove(beanName);
            this.registeredSingletons.add(beanName);
        }
    }
    getSingleton(beanName, new ObjectFactory<Object>(){
        public Object getObject() {
            try {
                return createBean(beanName, mbd, args);
            } catch (e) {
                throw e;
            }
        }
    });
    View Code

    5. 准备创建bean

    (1) 根据设置的class属性,或者根据className来解析class
    (2) 对override属性进行标记及验证
    (3) 应用初始化前的后处理器,解析指定bean是否存在初始化前的短路操作
    (4) 创建bean
    createBean(beanName, mbd, args) {
        // 根据设置的class属性,或者根据className来解析class
        resolveBeanClass(mbd, beanName);
        
        // 对override属性进行标记及验证
        try {
            mbd.prepareMethodOverrides();
        } catch (e) {
            throw e;
        }
        // 给BeanPostProcessors一个机会返回代理来替代真正的实例
        Object bean = resolveBeforeInstantiation(beanName, mbd);
        if (bean != null) {
            return bean;
        }
        // 创建bean
        Object beanInstance = doCreateBean(beanName, mbd, args);
        return beanInstance;
    }
    
    prepareMethodOverrides() {
        MethodOverrides methodOverrides = getMethodOverrides();
        for (MethodOverride mo : MethodOverrides) {
            prepareMethodOverride(mo);
        }
    }
    // lookup-method、replace-method属性
    prepareMethodOverride(mo) {
        // 获取对应类中对应方法名的个数
        int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
        if (count == 0) {
            throw e;
        } else if (count == 1) {
            // 标记未被覆盖,避免参数类型检查的开销
            mo.setOverloaded(false);
        }
    }
    |-- 实例化前置处理
    resolveBeforeInstantiation(beanName, mbd) {
        Object bean = null;
        try {
            bean = applyBeanPostProcessorsBeforeInitialization(mbd.getBeanClass(), beanName);
            if (bean != null) {
                bean = applyBeanPostProcessorsAfterInitialization(mbd.getBeanClass(), beanName);
            }
            mbd.beforeInstantiationResolved = (bean != null);
        } catch (e) {
            throw e;
        }
        return bean;
    }
    |-- 实例化前的处理器应用
    applyBeanPostProcessorsBeforeInitialization(beanClass, beanName) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
                Object result = ibp.postProcessorsBeforeInitialization(beanClass, beanName);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }
    |-- 实例化后的处理器应用
    applyBeanPostProcessorsAfterInitialization(existingBean, beanName) {
        
        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            Object result = beanProcessor.postProcessorsAfterInitialization(result, beanName);
            if (result != null) {
                return result;
            }
        }
        return result;
    }
    View Code

    6. 循环依赖

    (1) 循环依赖定义:
        循环依赖就是循环引用,就是存在2个或多个bean相互之间的持有对方,如:A->B->C->A,A->B->A
    (2) 循环依赖的类型:
        构造器循环依赖、setter循环依赖
    5.6.1 构造器循环依赖处理
        TestA、TestB、TestC
        TestA -> 查找“当前创建bean池”,如果没发现则继续准备构造器参数“testB”,并将“testA”标识符放到“当前创建bean池”
        TestB -> 查找“当前创建bean池”,如果没发现则继续准备构造器参数“testC”,并将“testB”标识符放到“当前创建bean池”
        TestC -> 查找“当前创建bean池”,如果没发现则继续准备构造器参数“testA”,并将“testC”标识符放到“当前创建bean池”
        准备构造器参数“testA”时,发现该 bean的标识符在“当前创建bean池”存在,抛出BeanCurrentlyInCreationException。
        
    5.6.2 setter循环依赖处理
        TestA、TestB、TestC
        TestA -> 暴露ObjectFactory工厂,并将“testA”标识符放到“当前创建bean池”,然后进行setter注入“testB”
        TestB -> 暴露ObjectFactory工厂,并将“testB”标识符放到“当前创建bean池”,然后进行setter注入“testC”
        TestC -> 暴露ObjectFactory工厂,并将“testC”标识符放到“当前创建bean池”,然后进行setter注入“testA”,进入注入“TestA”时由于提前暴露了“ObjectFactory”工厂,从而使用它返回提前暴露一个创建中的bean。
        最后依赖注入"TestB""TestA",完成setter注入。
        
    5.6.3 prototype范围的依赖处理
        scope="prototpye" -> 由于prototpye作用域无法完成依赖注入,spring容器不进行缓存prototype作用域的bean,因此无法提前暴露一个创建中的bean。
        scope="singleton" -> setAllowCircularReferences(false); // 禁用循环引用
    View Code

    7. 创建bean

    (1) 如果是单例则需要首先清除缓存
    (2) 实例化bean,将BeanDefinition转换为BeanWrapper
    (3) MergedBeanDefinitionPostProccessor的应用
    (4) 依赖处理
    (5) 属性填充
    (6) 循环依赖检查
    (7) 注册DisposableBean
    (8) 完成创建并返回
    protected Object doCreateBean(final String beanName, final RooBeanDefinition mbd, final Object[] args) {
        BeanWrapper instanceWrapper = null;
        // 如果是单例则需要首先清除缓存
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanObjectCache.remove(beanName);
        }
        // 实例化bean,将BeanDefinition转换为BeanWrapper
        if (instanceWrapper == null) {
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
        Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
        // MergedBeanDefinitionPostProccessor的应用
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                applyMergedBeanDefinitionPostProccessor(mbd, beanType, beanName);
            }
        }
        // 依赖处理
        // 是否需要提前暴露(单例&循环引用&当前bean正在创建中)
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletongCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            // 为避免循环依赖,在bean初始化完成前将创建实例的ObjectFactory加入工厂
            addSingletonFactory(beanName, new ObjectFactory(){
                public Object getObject() throw e {
                    // 对bean的再一次依赖引用
                    return getEarlyBeanReferences(beanName, mbd, bean);
                }
            });
        }
        
        Object exposedObject = bean;
        // 属性填充
        try {
            populateBean(beanName, mbd, instanceWrapper);
            if (exposedObject != null) {
                // 调用初始化方法,init-method
                exposedObject = initializeBean(beanName, exposedObject, mbd);
            }
        } catch (e) {
            throw e;
        }
        
        // 循环依赖检查
        if (earlySingletonExposure) {
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                // exposedObject没有在初始化方法改变,说明没有被增强
                if (exposedObject == null) {
                    exposedObject = earlySingletonReference;
                } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<String>();
                    for (String dependentBean : dependentBean) {
                        // 检测依赖
                        if (!removeSingletonIfCreateForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }
                    if (!actualDependentBeans.isEmpty()) {
                        throw e; 
                    }
                }
            }
        }
        
        // 注册DisposableBean
        try {
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        } catch (e) {
            throw e;
        }
        return exposedObject;
    }
    View Code

    7.1 属性的注入

    (1) InstantiationAwareBeanPostProcessor处理器的postProcessAfterInstantiation函数的应用,此函数可以控制程序是否继续进行属性填充
    (2) 根据类型,提取依赖bean,并统一存入PropertyValues中。
    (3) 应用InstantiationAwareBeanPostProcessor处理器的postProcessPropertyValues方法,对属性获取完毕填充前对属性的再次处理,RequiredAnnotationBeanPostProcessor对属性的验证
    (4) 将所有PropertyValues中的属性填充至BeanWrapper中
    populateBean(beanName, mbd, bw) {
        PropertyValues pvs = mbd.getPropertyValues();
        if (bw == null) {
            if (!pvs.isEmpty()) {
                throw e;
            } else {
                // 没有属性填充
                return ;
            }
        }
        
        boolean continueWithPropertyPopulation = true;
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                // 返回值是否继续填充bean
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
        // 如果后处理器发出停止填充命令则终止后续的执行
        if (!continueWithPropertyPopulation) {
            return;
        }
        
        if (mbd.getResolvedAutowireMode() == RooBeanDefinition.AUTOWIRE_BY_NAME || 
                mbd.getResolvedAutowireMode() == RooBeanDefinition.AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            if (mbd.getResolvedAutowireMode() == RooBeanDefinition.AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }
            if (mbd.getResolvedAutowireMode() == RooBeanDefinition.AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }
            pvs = newPvs;
        }
        
        // 后处理器已经初始化
        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        // 需要检查依赖
        boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
        if (hasInstAwareBpps || needsDepCheck) {
            PropertyDescriptor[] filteredPds = filterPropertyDescriptionsForDependencyCheck(bw);
            if (hasInstAwareBpps) {
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    // 对所有需要依赖检查的属性进行后处理
                    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvs == null) {
                        return;
                    }
                }
            } 
            if (needsDepCheck) {
                checkDependences(beanName, mbd, filteredPds, pvs);
            }
        }
        // 将属性应用到bean中
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
    // 根据name注入属性
    autowireByName(beanName, mbd, bw, newPvs) {
        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
        for (String propertyName : propertyNames) {
            if (containsBean(propertyName)) {
                // 递归初始化相关的bean
                Object bean = getBean(propertyName);
                pvs.add(propertyName, bean);
                // 注册依赖
                registerDependentBean(propertyName, beanName);
            } else {
                if (logger.isTraceEnabled()) {
                    logger.trace(...);
                }
            }
        }
    }
    // 根据type注入属性
    autowireByType(beanName, mbd, BeanWrapper bw, newPvs) {
        try {
            TypeConverter converter = getCustomTypeConverter();
            if (converter == null) {
                converter = bw;
            }
            
            Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
            // 寻找bw中需要依赖注入的属性
            String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
            for (String propertyName : propertyNames) {
                PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
                if (!Object.calss.equals(pd.getProperType())) {
                    // 探测指定的set方法
                    MethodParamter methodParam = BeanUtils.getWriteMethodParamter(pd);
                    boolean eager = PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
                    PropertyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                    
                    // 解析指定的属性所匹配的值,并把解析到的属性的名称存储在autowiredBeanNames中,当属性存在多个封装bean时:
                    // @Autowired private List<A> aList; 将会找到所有匹配A类型的bean将其注入
                    Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                    if (autowiredArgument != null) {
                        pvs.add(propertyName, autowiredArgument);
                    }
                    for (String autowiredBeanName : autowiredBeanNames) {
                        // 注册依赖
                        registerBeanDefinition(autowiredBeanName, beanName);
                    }
                    autowiredBeanNames.clear();
                }
            }
        } catch (e) {
            throw e;
        }
    }
    resolveDependency(descriptor, beanName, Set<String> autowiredBeanNames, typeConverter) {
        descriptor.initParamterNameDisconvery(getParamterNameDisconverer());
        // ObjectFactory类注入的特殊处理
        if (descriptor.getDependencyType().equals(ObjectFactory.class)) {
            return new DependencyObjectFactory(descriptor, beanName);
        }
        else if (... eq javaxInjectProviderClass) {
            return new DependencyObjectFactory().createDependencyProvider(descriptor, beanName);
        }
        else {
            // 通用逻辑处理
            return doResolvedDependency(descriptor, descriptor.getDependencyType(), beanName, autowiredBeanNames, typeConverter);
        }
    }
    doResolvedDependency(descriptor, descriptor.getDependencyType(), beanName, autowiredBeanNames, typeConverter) {
        // 用于支持spring中新增的注解@value
        Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
        if (value != null) {
            if (value instanceof String) {
                value = evaluateBeanDefinitionString(strVal, bd);
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return converter.convertIfNecessary(value, type);
        }
        
        // 属性是数组类型
        if (type.isArray()) { 
            // 数组类型
            Class<?> componentType = type.getComponentType();
            Map<String,Object> matchingBeans = findAutowireCandidates(beanName, componentType, descriptor);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(componentType, componentType.getName(), descriptor);
                }
                return null;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return converter.convertIfNecessary(matchingBeans.values(), type);
        }
        else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
            // 集合类型
            Class<?> elementType = descriptor.getCollectionType();
            if (elementType == null) {
                if (descriptor.isRequired()) {
                    throw e;
                }
                return null;
            }
            Map<String,Object> matchingBeans = findAutowireCandidates(beanName, componentType, descriptor);
            if (matchingBeans.isEmpty()) {
                throw e;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return converter.convertIfNecessary(matchingBeans.values(), type);
        } 
        else if (Map.class.isAssignableFrom(type) && type.isInterface()) {
            // Map类型
            Class<?> keyType = descriptor.getMapKeyType();
            if (keyType == null) {
                if (descriptor.isRequired()) {
                    throw e;
                }
                return null;
            }
            Map<String,Object> matchingBeans = findAutowireCandidates(beanName, componentType, descriptor);
            if (matchingBeans.isEmpty()) {
                throw e;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return converter.convertIfNecessary(matchingBeans.values(), type);
        }
        else {
            Map<String,Object> matchingBeans = findAutowireCandidates(beanName, componentType, descriptor);
            if (matchingBeans.isEmpty()) {
                throw e;
            }
            if (matchingBeans.size() > 1) {
                String primaryBeanName = determinePrimaryCandidate(matchingBeans, descriptor);
                if (primaryBeanName == null) {
                    throw e;
                }
                if (autowiredBeanNames != null) {
                    autowiredBeanNames.add(primaryBeanName);
                }
                return matchingBeans.get(primaryBeanName);
            }
            // 已经可以确定只有一个匹配项
            Map.Entry<String,Object> entry = matchingBeans.entrySet().iterator().next();
            if (autowiredBeanNames != null) {
                autowiredBeanNames.add(entry.getKey());
            }
            return entry.getValue();
        }
    }
    // 将属性应用到bean中
    applyPropertyValues(beanName, mbd, bw, pvs) {
        if (pvs == null || pvs.isEmpty()) {
            return;
        }
        
        MutablePropertyValues mpvs = null;
        List<PropertyValue> original;
        if (bw instancof BeanWrapperImpl) {
            ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
        }
        if (pvs instanceof MutablePropertyValues) {
            mpvs = (MutablePropertyValues) pvs;
            // 如果mpvs中的值已经被转换为对应的类型那么可以直接设置到beanWrapper中
            try {
                if (mpvs.isConverted()) {
                    bw.setPropertyValues(mpvs);
                    return;
                }
            } catch (e) {
                throw e;
            }
            original = mpvs.getPropertyValueList();
        } else {
            // 非MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法
            original = Arrays.asList(pvs.getPropertyValues());
        }
        
        TypeConverter converter = getCustomTypeConverter();
        if (converter == null) {
            converter = bw;
        }
        // 获取对应的解析器
        BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
        // Create a deep copy, resolving any references for values.
        List<PropertyValue> deepCopy = new ArrayList<String>(original.size());
        boolean resolveNecessary = false;
        for (PropertyValue pv : original) {
            if (pv.isConverted()) {
                deepCopy.add(pv);
            } else {
                String propertyName = pd.getName();
                Object originalValue = pd.getValue();
                Object resolvedValue = valueResolver.resolveValueIfNecessay(pv, originalValue);
                
                Object convertedValue = resolvedValue;
                boolean convertible = (bw.isWritableProperty(propertyName) && !PropertyUtils.isNestedIndexedProperty(propertyName));
                if (convertible) {
                    convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
                }
                if (convertedValue == originalValue) {
                    if (convertible) {
                        pv.setConvertedValue(convertedValue);
                    }
                    deepCopy.add(pv);
                }
                else if (convertible && originalValue instanceof TypedStringValue && 
                    !((TypedStringValue) originalValue).isDynamic() &&
                    !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))){
                    pv.setConvertedValue(convertedValue);
                    deepCopy.add(pv);
                }
                else {
                    resolveNecessary = true;
                    deepCopy.add(new PropertyValue(pv, convertedValue));
                }
            }
        }
        if (mpvs != null && !resolveNecessary) {
            mpvs.setConverted();
        }
        try {
            bw.setPropertyValues(new MutablePropertyValues(deepCopy));
        } catch (e) {
            throw e;
        }
    }
    View Code

    8. 初始化bean

    // spring容器已经执行过bean的实例化,并且进行了属性填充,而就是这时将会调用用户设定的初始化方法
    initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
        if (System.getSecurityMananger() != null) {
            AccessController.doPrivileged(new PrivilegedAction<Object>(){
                Object run() {
                    invokeAwareMethods(beanName, bean);
                    return null;
                }
            });
        } else {
            // 对特殊的bean处理:Aware、BeanClassLoaderAware、BeanFactoryAware
            invokeAwareMethods(beanName, bean);
        }
        
        Object wrappedBean = bean;
        if (mbd != null || !mbd.isSynthetic()) {
            // 应用前处理器
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }
        try {
            // 激活用户自定义的init方法
            invokeInitMethod(beanName, wrappedBean, mbd);
        } catch (e) {
            throw e;
        }
        if (mbd != null || !mbd.isSynthetic()) {
            // 后处理器应用
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }
        return wrappedBean;
    }
    invokeAwareMethods(final String beanName, final Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }
    // 处理器应用
    applyBeanPostProcessorsBeforeInitialization(existingBean, beanName) {
        Object result = existingBean;
        for ( BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            result = beanProcessor.postProcessBeforeInitialization(result, beanName);
            if (result == null) {
                return result;
            }
        }
        return result;
    }
    applyBeanPostProcessorsAfterInitialization(existingBean, beanName) {
        Object result = existingBean;
        for ( BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            result = beanProcessor.postProcessAfterInitialization(result, beanName);
            if (result == null) {
                return result;
            }
        }
        return result;
    }
    // 激活用户自定义的init方法
    invokeInitMethod(beanName, bean, mbd) {
        // 检查是否是InitializingBean,如果是则调用afterPropertiesSet方法
        boolean isInitializingBean = (bean istanceof InitializingBean);
        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){
                        Object run() {
                            ((InitializingBean) bean).afterPropertiesSet();
                            return null;
                        }
                    });
                } catch (e) {
                    throw e;
                }
            } else {
                ((InitializingBean) bean).afterPropertiesSet();
            }
        }
        if (mbd != null) {
            String initMethodName = mbd.getInitMethodName();
            if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName))
                && !mbd.isExternallyManagedInitMethod(initMethodName)) {
                // 调用自定义初始化方法
                invokeCustomInitMethod(beanName, bean, mbd);
            }
        }
    }
    View Code

    9. 注册DisposableBean

    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
        AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
        if (!mbd.isPrototype() && requiredDestruction(bean, mbd)) {
            if (mbd.isSingleton()) {
                // 单例模式下需要注册需要销毁的bean,此方法中会处理实现DisposableBean的bean,
                // 并且对所有的bean使用DestrunctionAwareBeanPostProccessors处理
                // DisposableBean DestrunctionAwareBeanPostProccessors
                registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            } else {
                scope scope = this.scopes.get(mgd.getScope());
                if (scope == null) {
                    throw e;
                }
                scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
        }
    }
    View Code
  • 相关阅读:
    帮助智力障碍的可怜儿童
    PE556
    ZJOIDay2T1 BB题解
    CTSC2016游记
    再次被老爸钦点退役
    欧拉筛
    考据
    51nod 1020 逆序排列(动态规划)
    51nod 1186 质数检测(Miller-Rabin算法)
    大整数类模板
  • 原文地址:https://www.cnblogs.com/ice-line/p/9967456.html
Copyright © 2020-2023  润新知