美文网首页
Spring4 属性填充源码

Spring4 属性填充源码

作者: sunpy | 来源:发表于2019-03-19 22:18 被阅读0次

介绍

Spring4的属性填充的方式是先根据名称(byName)或者类型(byType)解析,然后将解析的属性添加到PropertyValues集合,然后使用反射方式将属性值注入到属性中(其中采用setter方法注入,如果setter方法权限不够private的,那么就采用暴力反射setAccessible)。

属性填充开始位置

AbstractAutowireCapableBeanFactory类之populateBean方法

// 用bean定义中的属性值填充给定beanwrapper中的bean实例。
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    // 获取容器在解析Bean定义资源时为BeanDefiniton中设置的属性值
    PropertyValues pvs = mbd.getPropertyValues();
    // 实例对象为null
    if (bw == null) {
        // 属性值不为空 
        if (!pvs.isEmpty()) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        }
        else {
            //实例对象为null、属性值也为null
            return;
        }
    }

    boolean continueWithPropertyPopulation = true;
    // 在设置属性之前调用Bean的PostProcessor后置处理器  
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
    }

    if (!continueWithPropertyPopulation) {
        return;
    }
    // 依赖注入开始,首先处理autowire自动装配的注入
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

        // 对autowire自动装配的处理,根据Bean名称自动装配注入
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }

        // 根据Bean类型自动装配注入  
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }

        pvs = newPvs;
    }
    
    // 检查容器是否持有用于处理单例Bean关闭时的后置处理器  
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    // Bean实例对象没有依赖,即没有继承基类 
    boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

    if (hasInstAwareBpps || needsDepCheck) {
        // 从实例对象中提取属性描述符
        PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        if (hasInstAwareBpps) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    // 使用BeanPostProcessor处理器处理属性值  
                    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvs == null) {
                        return;
                    }
                }
            }
        }
        if (needsDepCheck) {
            // 检查属性的依赖
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
    }

    // 注入属性值
    applyPropertyValues(beanName, mbd, bw, pvs);
}

说明:

  1. 使用postProcessAfterInstantiation方法控制程序是否继续进行属性填充。
  2. 注入方式(byName / byType)获取依赖的bean,放入到PropertyValues。
  3. 使用postProcessPropertyValues方法对属性获取完毕填充前对属性的处理,譬如属性校验。
  4. 将所有PropertyValues中的属性填充至BeanWrapper中。

1. bean名称方式注入 --- byName

// IOC容器使用与Bean名称相匹配的属性类注入;autowire="byName"
protected void autowireByName(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 查找BeanWrapper中需要依赖注入的属性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    // 遍历属性名称
    for (String propertyName : propertyNames) {
        // 查找属性名称是否存在于singletonObjects或者beanDefinitionMap
        // 如果没找到判断parentBeanFactory是否存在属性名称
        if (containsBean(propertyName)) {
            // 递归初始化依赖的bean
            Object bean = getBean(propertyName);
            // 将初始化的bean,添加到pvs
            pvs.add(propertyName, bean);
            // 注册依赖
            registerDependentBean(propertyName, beanName);
            if (logger.isDebugEnabled()) {
                logger.debug("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");
            }
        }
    }
}
    // 注册依赖
    public void registerDependentBean(String beanName, String dependentBeanName) {
        String canonicalName = canonicalName(beanName);
        synchronized (this.dependentBeanMap) {
            Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
            if (dependentBeans == null) {
                dependentBeans = new LinkedHashSet<String>(8);
                this.dependentBeanMap.put(canonicalName, dependentBeans);
            }
            dependentBeans.add(dependentBeanName);
        }
        synchronized (this.dependenciesForBeanMap) {
            Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);
            if (dependenciesForBean == null) {
                dependenciesForBean = new LinkedHashSet<String>(8);
                this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);
            }
            dependenciesForBean.add(canonicalName);
        }
    }

说明:

  1. 获取BeanDefinition中PropertyValues属性名称数组。
  2. 遍历属性名称数组,将这些属性Bean添加到入参pvs(MutablePropertyValues)中。
  3. 分别将依赖的属性Bean进行注册。

2. bean类型方式注入 --- byType

// 根据Bean类型自动装配注入
protected void autowireByType(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 获取类型转换器
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
     
    Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
    // 查找BeanWrapper中需要依赖注入的属性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            // 获取属性描述对象
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            // 如果属性类型不等于Object类型
            if (!Object.class.equals(pd.getPropertyType())) {
                // 获取属性的setter方法
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                // Do not allow eager init for type matching in case of a prioritized post-processor.
                boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                // 解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中
                // 当属性存在多个封装bean时,将都会注入
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    // 将属性Bean添加到入参pvs(MutablePropertyValues)
                    pvs.add(propertyName, autowiredArgument);
                }
                // 遍历自动注入的beanName
                for (String autowiredBeanName : autowiredBeanNames) {
                    // 注册依赖
                    registerDependentBean(autowiredBeanName, beanName);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
                                propertyName + "' to bean named '" + autowiredBeanName + "'");
                    }
                }
                // 清空当前的集合容器
                autowiredBeanNames.clear();
            }
        }
        catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
        }
    }
}

说明:

  1. 获取BeanDefinition中PropertyValues属性名称数组。
  2. 解析beanName属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中(包括集合类型)。
  3. 将属性Bean添加到入参pvs(MutablePropertyValues)
  4. 注册依赖

3. 注入属性值

前面已经将所有的属性都添加到MutablePropertyValues集合中了。而将PropertyValues集合转化到BeanWrapper对象中就在当前这步操作了。

// 解析并注入属性值,解析此bean工厂中对其他bean的任何运行时引用。
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs == null || pvs.isEmpty()) {
        return;
    }

    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;

    if (System.getSecurityManager()!= null) {
        if (bw instanceof BeanWrapperImpl) {
            ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
        }
    }

    // 判断pvs是否为MutablePropertyValues类型
    if (pvs instanceof MutablePropertyValues) {
        // 强制类型转换为MutablePropertyValues类型
        mpvs = (MutablePropertyValues) pvs;
        // 如果mpvs中的值已经被转换为对应的类型,那么可以直接设置到beanWrapper中
        if (mpvs.isConverted()) {
            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 converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    // 创建一个Bean定义属性值解析器;将Bean定义中的属性值解析为Bean实例对象的实际值  
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

    List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(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);
            if (convertible) {
                // 使用用户自定义的类型转换器转换属性值
                convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
            }
            // 存储转换后的属性值,避免每次属性注入时的转换工作 
            if (resolvedValue == 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 (BeansException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
}

遍历PropertyValues中属性集合,为每一个属性赋值:

@Override
public void setPropertyValues(PropertyValues pvs) throws BeansException {
    setPropertyValues(pvs, false, false);
}

@Override
public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
        throws BeansException {

    List<PropertyAccessException> propertyAccessExceptions = null;
    // 获取PropertyValue类型List
    List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues ?
            ((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));
    // 遍历propertyValues
    for (PropertyValue pv : propertyValues) {
        try {
            // 设置PropertyValue
            setPropertyValue(pv);
        }
        catch (NotWritablePropertyException ex) {
            if (!ignoreUnknown) {
                throw ex;
            }
            // Otherwise, just ignore it and continue...
        }
        catch (NullValueInNestedPathException ex) {
            if (!ignoreInvalid) {
                throw ex;
            }
            // Otherwise, just ignore it and continue...
        }
        catch (PropertyAccessException ex) {
            if (propertyAccessExceptions == null) {
                propertyAccessExceptions = new LinkedList<PropertyAccessException>();
            }
            propertyAccessExceptions.add(ex);
        }
    }

    // If we encountered individual exceptions, throw the composite exception.
    if (propertyAccessExceptions != null) {
        PropertyAccessException[] paeArray =
                propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]);
        throw new PropertyBatchUpdateException(paeArray);
    }
}

@Override
public void setPropertyValue(PropertyValue pv) throws BeansException {
    PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens;
    if (tokens == null) {
        String propertyName = pv.getName();
        BeanWrapperImpl nestedBw;
        try {
            // 通过给定的属性名称获取BeanWrapper
            nestedBw = getBeanWrapperForPropertyPath(propertyName);
        }
        catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Nested property in path '" + propertyName + "' does not exist", ex);
        }
        // 解析给定属性名称为PropertyTokenHolder
        tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName));
        if (nestedBw == this) {
            pv.getOriginalPropertyValue().resolvedTokens = tokens;
        }
        // 真正设置属性值
        nestedBw.setPropertyValue(tokens, pv);
    }
    else {
        setPropertyValue(tokens, pv);
    }
}

说明:

  1. 将PropertyValues转换为List<PropertyValue>对象。
  2. 遍历集合List<PropertyValue>。
  3. resolveValueIfNecessary方法将属性引用转换为IoC容器中实例化Bean引用。
  4. setPropertyValues方法;将属性值注入。

关键方法设计:单个属性值注入到属性中

// 真正依赖注入属性值
@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    // 获取属性名称
    String propertyName = tokens.canonicalName;
    // 获取全名称
    String actualName = tokens.actualName;
    // keys是用来保存集合类型属性的size
    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;
        try {
            // 获取属性值,该方法内部使用JDK的内省( Introspector)机制,
            // 调用属性的getter(readerMethod)方法,获取属性的值
            propValue = getPropertyValue(getterTokens);
        }
        catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " +
                    "in indexed property path '" + propertyName + "'", ex);
        }

        // 获取集合长度
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (this.autoGrowNestedPaths) {
                // TODO: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            }
            else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " +
                        "in indexed property path '" + propertyName + "': returned null");
            }
        }
        // 属性值类型为数组类型
        if (propValue.getClass().isArray()) {
            // 获取属性的描述符
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            // 获取数组类型
            Class<?> requiredType = propValue.getClass().getComponentType();
            // 获取数组长度
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                // 将属性的值赋值给数组中的元素
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
                        requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            }
            catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        }
        // 属性值类型为List集合类型
        else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            // 获取list集合类型 
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
                    pd.getReadMethod(), tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            // 获取list集合size 
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            // 获取list解析后的属性值
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
                    requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            // 如果list的长度大于属性值的长度,将多余的位置赋值为null
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    }
                    catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " +
                                size + ", accessed using property path '" + propertyName +
                                "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            }
            else {
                try {
                    // 使用下标设置属性值
                    list.set(index, convertedValue);
                }
                catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        }
        // 属性值类型为Map集合类型
        else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            // 获取Map集合key类型
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
                    pd.getReadMethod(), tokens.keys.length);
            // 获取Map集合value类型
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
                    pd.getReadMethod(), tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            TypeDescriptor typeDescriptor = (mapKeyType != null ?
                    TypeDescriptor.valueOf(mapKeyType) : TypeDescriptor.valueOf(Object.class));
            // 解析Map类型属性key值
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // 解析Map类型属性value值
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
                    mapValueType, TypeDescriptor.nested(property(pd), tokens.keys.length));
            // 将解析后的key和value值赋值给Map集合属性 
            map.put(convertedMapKey, convertedMapValue);
        }
        else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName +
                    "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]");
        }
    }
    // 属性类型为非集合类型注入
    else {
        // 获取属性值的描述
        PropertyDescriptor pd = pv.resolvedDescriptor;
        
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            // 如果属性描述为空或者属性的setter方法也为空
            if (pd == null || pd.getWriteMethod() == null) {
                //如果属性值是可选的,则返回(忽略该属性值)
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName +
                            "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                }
                else { // 否则抛出不可写属性异常NotWritablePropertyException
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(
                            getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            // 设置缓存属性解析描述为pd
            pv.getOriginalPropertyValue().resolvedDescriptor = pd;
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                }
                else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        // 利用JDK内省机制获取属性的getter方法 
                        final Method readMethod = pd.getReadMethod();
                        // 如果属性的getter方法不是public访问控制权限的  
                        // 那么使用JDK的反射机制强行访问非public的方法(暴力读取属性值) 
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) &&
                                !readMethod.isAccessible()) {
                            if (System.getSecurityManager()!= null) {
                                // 匿名内部类,根据权限修改属性的读取控制限制
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            }
                            else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            // 属性没有提供getter方法时,调用潜在的读取属性值的方法,获取属性值
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                                    @Override
                                    public Object run() throws Exception {
                                        return readMethod.invoke(object);
                                    }
                                }, acc);
                            }
                            else {
                                oldValue = readMethod.invoke(object);
                            }
                        }
                        catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" +
                                        this.nestedPath + propertyName + "'", ex);
                            }
                        }
                    }
                    // 解析属性值
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd, new TypeDescriptor(property(pd)));
                }
                // 设置属性的注入值
                pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
            }
            // 根据JDK的内省机制,获取属性的setter(写方法)方法
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ?
                    ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() :
                    pd.getWriteMethod());
            // 如果属性的setter方法是非public,即访问控制权限比较严格,则使用JDK的反射机制,  
            // 强行设置setter方法可访问(暴力为属性赋值)
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) {
                if (System.getSecurityManager()!= null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                }
                else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    // 将属性值设置到属性字段上
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                }
                catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            }
            else {
                writeMethod.invoke(this.object, value);
            }
        }
        catch (TypeMismatchException ex) {
            throw ex;
        }
        catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent =
                    new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
            }
            else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        }
        catch (Exception ex) {
            PropertyChangeEvent pce =
                    new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

相关文章

网友评论

      本文标题:Spring4 属性填充源码

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