美文网首页
spring容器之bean的属性填充

spring容器之bean的属性填充

作者: 会上树的程序猿 | 来源:发表于2019-07-21 21:48 被阅读0次

    在我们刚学习spring对bean的创建时,我们在方法#doCreateBean()方法中,其主要通过创建bean和一些初始化工作,大概有4个过程分别是:

    • 调用#createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) 方法,来进行bean的创建
    • 对于单例模式的bean进行循环依赖的检查
    • 通过调用#populateBean(beanName, mbd, instanceWrapper)来实现对刚创建的bean进行属性的填充
    • 最后调用#initializeBean(beanName, exposedObject, mbd)完成bean的初始化

    关于bean的创建我们在前面的篇章中已经完成了,接下来我们看看对于已完成bean的属性的填充,直接来看代码:

    AbstractAutowireCapableBeanFactory.java
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        //没有被封装的bean实例
        if (bw == null) {
            //如果有属性,则抛出BeanCreationException异常
            if (mbd.hasPropertyValues()) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
            else {
                // Skip property population phase for null instance.
                //没有可填充的属性
                return;
            }
        }
    
        // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
        // state of the bean before properties are set. This can be used, for example,
        // to support styles of field injection.
        //1.在属性填充前,给InstantiationAwareBeanPostProcessor最后一次来改变bean的机会
        boolean continueWithPropertyPopulation = true;
        //通过mbd.isSynthetic()来判断当前bean的定义是否是合成的,而不是由应用来定义的
        //通过hasInstantiationAwareBeanPostProcessors来判断当前bean是否持有 InstantiationAwareBeanPostProcessor
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            //循环遍历beanPostProcessors
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                //如果为InstantiationAwareBeanPostProcessor类型的
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    //赋值即可
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    //返回的值为是否为继续填充bean
                    //postProcessAfterInstantiation:如果应该在 bean上面设置属性则返回 true,否则返回 false,但是一般默认为true
                    //如果返回false的话,将会阻止在此 Bean实例上调用任何后续的InstantiationAwareBeanPostProcessor实例
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        continueWithPropertyPopulation = false;
                        break;
                    }
                }
            }
        }
        //如果后续处理器发出停止填充命令,则终止后续操作
        if (!continueWithPropertyPopulation) {
            return;
        }
        //2.从rootBeanDefinition中获取bean的属性值
        PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
        //获取resolvedAutowireMode的编码
        int resolvedAutowireMode = mbd.getResolvedAutowireMode();
        //如果编码为AUTOWIRE_BY_NAME为1或者AUTOWIRE_BY_TYPE为2
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            //对PropertyValues属性进行封装成MutablePropertyValues对象
            //因为MutablePropertyValues主要是可以对构造函数进行深度的拷贝,以及属性的操作,这样可以保证我们的属性值是独立的
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            // Add property values based on autowire by name if applicable.
            //根据名称自动注入
            if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }
            // Add property values based on autowire by type if applicable.
            //根据类型自动注入
            if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }
            pvs = newPvs;
        }
        //是否已经初始化好后置处理器
        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        //是否需要依赖检查
        boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
        //3.bean的后置处理过程
        PropertyDescriptor[] filteredPds = null;
        if (hasInstAwareBpps) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            //遍历BeanPostProcessor进行处理
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                //
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    //对所有需要依赖检查的属性进行后置处理
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                    //从BeanWrapper中进行PropertyDescriptor结果集的提取
                    //对于PropertyDescriptor:描述一个java Bean的属性,可以通过一对方法可以提取一个属性
                    if (pvsToUse == null) {
                        if (filteredPds == null) {
                            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                        }
                        pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvsToUse == null) {
                            return;
                        }
                    }
                    pvs = pvsToUse;
                }
            }
        }//4.依赖检查
        if (needsDepCheck) {
            if (filteredPds == null) {
                filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            }
            //依赖检查,其中对应的是我们配置文件的属性depens -on属性
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
        //5. 将属性应用到bean中
        if (pvs != null) {
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
    }
    

    简单的梳理下该方法的流程:

    • 在1处,通过hasInstantiationAwareBeanPostProcessors属性来判断,在属性填充前,给InstantiationAwareBeanPostProcessor最后一次来改变bean的机会,此过程可以控制是否继续进行属性的填充

    • 在2处,根据AbstractBeanDefinition#getResolvedAutowireMode()返回的值来判断是以什么样的方式注入的,然后统一存放在PorpertyValues中.

    • 根据名称来自动注入:autowireByName(beanName, mbd, bw, newPvs);

    • 根据类型来自动注入: autowireByType(beanName, mbd, bw, newPvs);

    • 在3处,进行后置处理

    • 在4处,需进行依赖检查

    • 在5处,将属性应用到bean中

    接下来我们分别来看上述流程的每一个详细的过程

    根据不同的值来自动注入

    在spring中是主要通过两种不同的类型来注入的,是根据AbstractBeanDefinition#getResolvedAutowireMode()方法的值来做判断,来看代码:

    //<1>获取resolvedAutowireMode的编码
    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
        //如果编码为AUTOWIRE_BY_NAME为1或者AUTOWIRE_BY_TYPE为2
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            //对PropertyValues属性进行封装成MutablePropertyValues对象
            //因为MutablePropertyValues主要是可以对构造函数进行深度的拷贝,以及属性的操作,这样可以保证我们的属性值是独立的
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            // Add property values based on autowire by name if applicable.
            //根据名称自动注入
            if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }
            // Add property values based on autowire by type if applicable.
            //根据类型自动注入
            if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }
            pvs = newPvs;
        }
    

    这就是这段根据不同类型来注入的部分代码,我们来看<1>处:

    AbstractBeanDefinition.java
    private int autowireMode = AUTOWIRE_NO;
    public int getResolvedAutowireMode() {
        if (this.autowireMode == AUTOWIRE_AUTODETECT) {
            // Work out whether to apply setter autowiring or constructor autowiring.
            // If it has a no-arg constructor it's deemed to be setter autowiring,
            // otherwise we'll try constructor autowiring.
            Constructor<?>[] constructors = getBeanClass().getConstructors();
            for (Constructor<?> constructor : constructors) {
                if (constructor.getParameterCount() == 0) {
                    return AUTOWIRE_BY_TYPE;
                }
            }
            return AUTOWIRE_CONSTRUCTOR;
        }
        else {
            return this.autowireMode;
        }
    }
    

    这点代码主要的作用就是获取一个注入的类型,如果返回的值为1,则是通过名称去注入,如果是2,则是通过类型去注入,我们来看根据名称注入的过程:

    autowireByName(根据名称去注入)

    该方法是在#autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs)中,接着看:

    protected void autowireByName(
            String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
        //<1>.在bw中寻找需要注入的属性名称
        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
        //遍历处理
        for (String propertyName : propertyNames) {
            //如果容器中存在相关bean的名称
            if (containsBean(propertyName)) {
                //递归初始化相关的bean
                Object bean = getBean(propertyName);
                //给指定名称属性绑定值
                pvs.add(propertyName, bean);
                //给相关依赖的bean注册属性
                registerDependentBean(propertyName, beanName);
                if (logger.isTraceEnabled()) {
                    logger.trace("Added autowiring by name from bean name '" + beanName +
                            "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
                }
            }
            else {
                if (logger.isTraceEnabled()) {
                    logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
                            "' by name: no matching bean found");
                }
            }
        }
    }
    

    该方法逻辑很清晰,首先寻找需要进行绑定属性的名称,也就是上述代码中的<1>处的方法,代码如下:

    protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
        Set<String> result = new TreeSet<>();
        //从beanDefinition中获取属性值
        PropertyValues pvs = mbd.getPropertyValues();
        PropertyDescriptor[] pds = bw.getPropertyDescriptors();
        //遍历处理
        for (PropertyDescriptor pd : pds) {
            if (pd.getWriteMethod() != null //有可写的方法
                    && !isExcludedFromDependencyCheck(pd) //依赖检测没有被忽略的
                    && !pvs.contains(pd.getName())//在pvs中不包含该属性名
                    && !BeanUtils.isSimpleProperty(pd.getPropertyType())) {//不是简单型的类型
                //添加
                result.add(pd.getName());
            }
        }
        return StringUtils.toStringArray(result);
    }
    

    获取到了属性的简易名称,接着是递归处理和给bean设置属性值,在绑定的过程中可能会有依赖问题的处理,那么我们当然还是先要给依赖的bean进行相关属性的设置,看代码:

    DefaultSinglegtonBeanRegistry.java
    /**保存的是依赖beanName之间的映射关系*/
    private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
    /**
     * 给当前bean注册一个依赖的bean
     * @param beanName 当前要创建的bean
     * @param dependentBeanName 当前bean所依赖的bean的名字
     */
    public void registerDependentBean(String beanName, String dependentBeanName) {
        //获取原始beanName
        String canonicalName = canonicalName(beanName);
        // 添加 <canonicalName, <dependentBeanName>> 到 dependentBeanMap 中
        synchronized (this.dependentBeanMap) {
            Set<String> dependentBeans =
                    this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
            if (!dependentBeans.add(dependentBeanName)) {
                return;
            }
        }
        //同上
        synchronized (this.dependenciesForBeanMap) {
            Set<String> dependenciesForBean =
                    this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
            dependenciesForBean.add(canonicalName);
        }
    }
    
    根据类型自动注入(autowireByType)

    关于类型注入是通过#autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) 方法来完成自动注入的,直接看代码:

    protected void autowireByType(
            String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
        //获取自定义的TypeConverter实例
        //主要的作用是代替PropertyEditor机制
        TypeConverter converter = getCustomTypeConverter();
        if (converter == null) {
            converter = bw;
        }
    
        Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
        //获取非简单的属性名称(也就是在bw中去获取需要依赖注入的属性名称)
        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
        //遍历处理
        for (String propertyName : propertyNames) {
            try {
                //获取PropertyDescriptor实例
                PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
                // Don't try autowiring by type for type Object: never makes sense,
                // even if it technically is a unsatisfied, non-simple property.
                //不要通过类型去尝试着注入,因为它可能不是一个简单的属性,可能是多重属性的依赖关系
                if (Object.class != pd.getPropertyType()) {
                    //探测指定属性的set方法
                    MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                    // Do not allow eager init for type matching in case of a prioritized post-processor.
                    boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                    DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                    // 解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中
                    // 当属性存在多个封装bean时将会找到所有匹配的bean并将其注入
                    Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                    if (autowiredArgument != null) {
                        pvs.add(propertyName, autowiredArgument);
                    }
                    //遍历处理,并注册相关依赖的bean的属性
                    for (String autowiredBeanName : autowiredBeanNames) {
                        registerDependentBean(autowiredBeanName, beanName);
                        if (logger.isTraceEnabled()) {
                            logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
                                    propertyName + "' to bean named '" + autowiredBeanName + "'");
                        }
                    }
                    //清空autowiredBeanNames数组
                    autowiredBeanNames.clear();
                }
            }
            catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
            }
        }
    }
    

    我们可以发现,通过名称和类型实现自动属性的注入很类似,首先都是在bw中去寻找需要依赖注入的属性,然后就是遍历处理匹配bean进行属性的设置,最后对于依赖同样也是做了处理,在根据类型去自动注入的过程中,有一个方法需要注意#resolveDependency(desc, beanName, autowiredBeanNames, converter),该方法主要是在注入前完成一些依赖解析工作,代码如下:

    public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
            @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
        //获取一个ParameterNameDiscoverer实例
        //初始化方法所需的参数
        descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
        //如果注入的是Optional类型,通过createOptionalDependency来处理
        if (Optional.class == descriptor.getDependencyType()) {
            return createOptionalDependency(descriptor, requestingBeanName);
        }
        //如果依赖的类型为ObjectFactory或者是ObjectProvider类型的
        else if (ObjectFactory.class == descriptor.getDependencyType() ||
                ObjectProvider.class == descriptor.getDependencyType()) {
            return new DependencyObjectProvider(descriptor, requestingBeanName);
        }
        //如果是javaxInjectProviderClass类型的依赖,需要做特殊的处理操作
        else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
            return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
        }
        //
        else {
            //通过#getLazyResolutionProxyIfNecessary(...)方法为实际依赖目标的延迟解析构建代理。
            //默认是null
            Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
                    descriptor, requestingBeanName);
            if (result == null) {
                //<...>这里是通用的处理逻辑
                result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
            }
            return result;
        }
    }
    

    上面方法的处理过程中,我们可以发现真正的核心在<...>处,接着看:

    public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
            @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
        //获取一个注入点实例
        InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
        try {
            // 针对给定的工厂给定一个快捷实现的方式,例如考虑一些预先解析的信息
            // 在进入所有bean的常规类型匹配算法之前,解析算法将首先尝试通过此方法解析快捷方式。
            // 子类可以覆盖此方法
            Object shortcut = descriptor.resolveShortcut(this);
            //如果存在此快捷信息,则返回
            if (shortcut != null) {
                return shortcut;
            }
            //获取依赖的类型
            Class<?> type = descriptor.getDependencyType();
            //此处主要是用于支持spring的@value注解
            Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
            if (value != null) {
                if (value instanceof String) {
                    String strVal = resolveEmbeddedValue((String) value);
                    BeanDefinition bd = (beanName != null && containsBean(beanName) ?
                            getMergedBeanDefinition(beanName) : null);
                    value = evaluateBeanDefinitionString(strVal, bd);
                }
                TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
                try {
                    return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
                }
                catch (UnsupportedOperationException ex) {
                    // A custom TypeConverter which does not support TypeDescriptor resolution...
                    return (descriptor.getField() != null ?
                            converter.convertIfNecessary(value, type, descriptor.getField()) :
                            converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
                }
            }
            //解析复合的bean,实质还是解析bean的属性
            //不过考虑到了map array list等类型的
            Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
            if (multipleBeans != null) {
                return multipleBeans;
            }
            //查找匹配类型相同的bean实例
            // 返回的类型结构为:key = 匹配的beanName,value = beanName对应的实例化bean
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
            //没找到,检验@autowire 的require是否为 true
            if (matchingBeans.isEmpty()) {
                //如果的require为true且没有找到,直接抛raiseNoMatchingBeanFound异常
                if (isRequired(descriptor)) {
                    raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
                }
                return null;
            }
    
            String autowiredBeanName;
            Object instanceCandidate;
            //找到了,确定给定bean的autowire的候选者
            if (matchingBeans.size() > 1) {
                autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
                if (autowiredBeanName == null) {
                    if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
                        //唯一性的检查处理过程
                        return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
                    }
                    else {
                        // In case of an optional Collection/Map, silently ignore a non-unique case:
                        // possibly it was meant to be an empty collection of multiple regular beans
                        // (before 4.3 in particular when we didn't even look for collection beans).
                        return null;
                    }
                }
                //最后从matchingBeans取出
                instanceCandidate = matchingBeans.get(autowiredBeanName);
            }
            else {
                // We have exactly one match.
                //已经确认了只有一个匹配项
                Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
                autowiredBeanName = entry.getKey();
                instanceCandidate = entry.getValue();
            }
    
            if (autowiredBeanNames != null) {
                autowiredBeanNames.add(autowiredBeanName);
            }
            if (instanceCandidate instanceof Class) {
                instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
            }
            Object result = instanceCandidate;
            if (result instanceof NullBean) {
                if (isRequired(descriptor)) {
                    raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
                }
                result = null;
            }
            if (!ClassUtils.isAssignableValue(type, result)) {
                throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
            }
            return result;
        }
        finally {
            //把它设置为一个注入点
            ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
        }
    }
    

    到这里我们的属性填充基本上完事,按照我们的方法populateBean(...)的大致流程完成属性填充之后,接着是进行后置处理操作,这里我们先放过,后续来说,接下来我们来看一下将属性应用到bean中的过程:

    applyPropertyValues

    在populateBean(...)的代码片段中,首先是从beanDefinition中获取到属性的值,接着对PropertyValues属性值进行了封装成MutablePropertyValues的对象,经过一系列的处理最后通过#applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) 方法将属性应用到具体的bean中,我们来看代码实现:

    protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
        if (pvs.isEmpty()) {
            return;
        }
    
        //设置当前BeanWrapperImpl的SecurityContext环境
        if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
            ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
        }
        //一种是MutablePropertyValues类型的
        MutablePropertyValues mpvs = null;
        //一种是original的类型的
        List<PropertyValue> original;
        //获取original类型
        if (pvs instanceof MutablePropertyValues) {
            mpvs = (MutablePropertyValues) pvs;
            //如果已经转换了类型
            if (mpvs.isConverted()) {
                // Shortcut: use the pre-converted values as-is.
                try {
                    //给相应的实例设置属性值,这里才是依赖注入的真正实现的地方
                    bw.setPropertyValues(mpvs);
                    return;
                }
                catch (BeansException ex) {
                    throw new BeanCreationException(
                            mbd.getResourceDescription(), beanName, "Error setting property values", ex);
                }
            }
            original = mpvs.getPropertyValueList();
        }
        else {
            //如果pvs不是MutablePropertyValues类型的,那么直接使用原始的属性获取方法
            original = Arrays.asList(pvs.getPropertyValues());
        }
        //获取自定义TypeConverter类型
        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<>(original.size());
        boolean resolveNecessary = false;
        //遍历属性,同时将属性转换为对应类的对应属性的类型
        for (PropertyValue pv : original) {
            if (pv.isConverted()) {
                deepCopy.add(pv);
            }
            //转换对应属性的属性值
            else {
                String propertyName = pv.getName();
                Object originalValue = pv.getValue();
                //转换属性值,比如:将当前的引用转换为IOC容器中的实例化对象的引用
                Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
                Object convertedValue = resolvedValue;
                //判断属性值是否可以转换
                boolean convertible = bw.isWritableProperty(propertyName) &&
                        !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
                //通过自定义的TypeConverter类型进行属性值的转换
                if (convertible) {
                    convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
                }
                // Possibly store converted value in merged bean definition,
                // in order to avoid re-conversion for every created bean instance.
                //对转换后的属性值进行保存,避免之后每次创建实例重复转换工作
                if (resolvedValue == originalValue) {
                    if (convertible) {
                        //设置转换后的值给pv
                        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();
        }
    
        // Set our (possibly massaged) deep copy.
        //这里是属性依赖注入的实现点
        try {
            bw.setPropertyValues(new MutablePropertyValues(deepCopy));
        }
        catch (BeansException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Error setting property values", ex);
        }
    }
    

    上面就是applyPropertyValues方法的分析过程其主要是围绕着两个点来展开:

    • 在进行属性值的注入时,如果属性值不需要转换,那么直接进行注入即可.
    • 当需要对属性值进行转换时,首先是转换成对应类的属性的属性值,接着设置,最后完成注入

    大致的就是分为这两类进行属性值的注入,如果需要转换属性值,这里涉及到了转换的方法#resolveValueIfNecessary(Object argName, @Nullable Object value),该方法我们后面详细来说,这里大家先知道一下,到这里我们已经完成了doCreateBean(...)的第二个阶段,我们的属性填充已经完成...

    相关文章

      网友评论

          本文标题:spring容器之bean的属性填充

          本文链接:https://www.haomeiwen.com/subject/fbdulctx.html