亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring?populateBean屬性賦值和自動(dòng)注入

 更新時(shí)間:2023年03月14日 15:30:38   作者:無(wú)名之輩J  
這篇文章主要為大家介紹了Spring?populateBean屬性賦值和自動(dòng)注入示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
   if (bw == null) {
      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.
   //一、修改Bean實(shí)例
   //給InstantiationAwareBeanPostProcessors最后一個(gè)機(jī)會(huì)在屬性設(shè)置前改變bean
   // 具體通過(guò)調(diào)用ibp.postProcessAfterInstantiation方法,如果調(diào)用返回false,表示不必繼續(xù)進(jìn)行依賴(lài)注入,直接返回
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            //返回值為true則繼續(xù)填充bean
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               return;
            }
         }
      }
   }
   PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
    // 根據(jù)bean的依賴(lài)注入方式:即是否標(biāo)注有 @Autowired 注解或 autowire=“byType/byName” 的標(biāo)簽
   // 會(huì)遍歷bean中的屬性,根據(jù)類(lèi)型或名稱(chēng)來(lái)完成相應(yīng)的注入
   int resolvedAutowireMode = mbd.getResolvedAutowireMode();
   if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      // Add property values based on autowire by name if applicable.
      //二、根據(jù)名稱(chēng)自動(dòng)注入
      if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }
      // Add property values based on autowire by type if applicable.
      //三、根據(jù)類(lèi)型自動(dòng)注入
      if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }
      pvs = newPvs;
   }
    // 容器是否注冊(cè)了InstantiationAwareBeanPostProcessor
   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   // 是否進(jìn)行依賴(lài)檢查
   boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
   PropertyDescriptor[] filteredPds = null;
   if (hasInstAwareBpps) {
      if (pvs == null) {
         pvs = mbd.getPropertyValues();
      }
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
               if (filteredPds == null) {
                  filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
               }
               //對(duì)所有需要依賴(lài)檢查的屬性進(jìn)行后處理
               //四、處理屬性值(@Autowired、@Value)
               pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
               if (pvsToUse == null) {
                  return;
               }
            }
            pvs = pvsToUse;
         }
      }
   }
   // 檢查是否滿(mǎn)足相關(guān)依賴(lài)關(guān)系,對(duì)應(yīng)的depends-on屬性,3.0后已棄用
   if (needsDepCheck) {
      if (filteredPds == null) {
         filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      }
      checkDependencies(beanName, mbd, filteredPds, pvs);
   }
   // 五、填充屬性
   if (pvs != null) {
      applyPropertyValues(beanName, mbd, bw, pvs);
   }
}

一、postProcessAfterInstantiation:修改Bean實(shí)例

在填充屬性之前調(diào)用postProcessAfterInstantiation修改Bean定義信息

if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof InstantiationAwareBeanPostProcessor) {
         InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
         if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
            return;
         }
      }
   }
}

二、autowireByName:根據(jù)名稱(chēng)自動(dòng)注入

protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    //尋找bw中需要依賴(lài)注入的屬性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        //檢查緩存bean中是否存在當(dāng)前bean
        if (containsBean(propertyName)) {
            //遞歸初始化相關(guān)的bean. 代碼(1)
            Object bean = getBean(propertyName);
            pvs.add(propertyName, bean);
            //注冊(cè)依賴(lài)
            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");
            }
        }
    }
}

三、autowireByType:根據(jù)類(lèi)型自動(dòng)注入

protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 獲取自定義的類(lèi)型轉(zhuǎn)換器
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    //尋找bw中需要依賴(lài)注入的屬性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            // 獲取屬性描述符
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            //不要嘗試按類(lèi)型為Object類(lèi)型自動(dòng)裝配:即使從技術(shù)上講是不滿(mǎn)意的,非簡(jiǎn)單的屬性,也沒(méi)有意義。
            if (Object.class != pd.getPropertyType()) {
                //探測(cè)指定屬性的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的屬性所匹配的值,并把解析到的屬性名稱(chēng)存儲(chǔ)在autowiredBeanNames中,當(dāng)屬性存在多個(gè)封裝bean時(shí)
                //比如: @Autowired private List<A> aList; 就會(huì)找到所有匹配A類(lèi)型的bean并將其注入
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    // 添加到待注入的bean列表中
                    pvs.add(propertyName, autowiredArgument);
                }
                for (String autowiredBeanName : autowiredBeanNames) {
                    //注冊(cè)依賴(lài)
                    registerDependentBean(autowiredBeanName, beanName);
                    if (logger.isTraceEnabled()) {
                        logger.trace("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);
        }
    }
}

四、postProcessPropertyValues:處理屬性值(@Resource、@Autowired、@Value)

CommonAnnotationBeanPostProcessor:處理@Resource

AutowiredAnnotationBeanPostProcessor:處理@Autowired、@Value。

詳情:http://chabaoo.cn/article/277330.htm

五、applyPropertyValues:填充屬性

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs.isEmpty()) {
        return;
    }
    if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
        ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
    }
    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;
    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        //如果mpvs中的值已經(jīng)被轉(zhuǎn)換為對(duì)應(yīng)的類(lèi)型那么可以直接設(shè)置到beanWrapper
        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封裝的類(lèi)型,那么直接使用原始的屬性獲取方法
        original = Arrays.asList(pvs.getPropertyValues());
    }
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    //獲取對(duì)應(yīng)的解析器
    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;
    //遍歷屬性,將屬性轉(zhuǎn)換為對(duì)應(yīng)屬性的類(lèi)型
    for (PropertyValue pv : original) {
        if (pv.isConverted()) {
            deepCopy.add(pv);
        } else {
            String propertyName = pv.getName();
            Object originalValue = pv.getValue();
            if (originalValue == AutowiredPropertyMarker.INSTANCE) {
                Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
                if (writeMethod == null) {
                    throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
                }
                originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
            }
            //解析、注入值
            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);
            }
            // 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.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);
    }
}

解析、注入值

public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
    // We must check each value to see whether it requires a runtime reference
    // to another bean to be resolved.
    // 5.1 解析引用
    if (value instanceof RuntimeBeanReference) {
        RuntimeBeanReference ref = (RuntimeBeanReference) value;
        return resolveReference(argName, ref);
    }
    // 如果根據(jù)另一個(gè)Bean的name進(jìn)行依賴(lài),進(jìn)入下面的分支
    else if (value instanceof RuntimeBeanNameReference) {
        String refName = ((RuntimeBeanNameReference) value).getBeanName();
        refName = String.valueOf(doEvaluate(refName));
        if (!this.beanFactory.containsBean(refName)) {
            throw new BeanDefinitionStoreException(
                    "Invalid bean name '" + refName + "' in bean reference for " + argName);
        }
        return refName;
    }
    // 解析BeanDefinitionHolder
    else if (value instanceof BeanDefinitionHolder) {
        // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
        BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
        return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
    }
    // 解析純BeanDefinition
    else if (value instanceof BeanDefinition) {
        // Resolve plain BeanDefinition, without contained name: use dummy name.
        BeanDefinition bd = (BeanDefinition) value;
        String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
                ObjectUtils.getIdentityHexString(bd);
        return resolveInnerBean(argName, innerBeanName, bd);
    }
    // 解析數(shù)組
    else if (value instanceof ManagedArray) {
        // May need to resolve contained runtime references.
        ManagedArray array = (ManagedArray) value;
        Class<?> elementType = array.resolvedElementType;
        if (elementType == null) {
            String elementTypeName = array.getElementTypeName();
            if (StringUtils.hasText(elementTypeName)) {
                try {
                    elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
                    array.resolvedElementType = elementType;
                }
                catch (Throwable ex) {
                    // Improve the message by showing the context.
                    throw new BeanCreationException(
                            this.beanDefinition.getResourceDescription(), this.beanName,
                            "Error resolving array type for " + argName, ex);
                }
            }
            else {
                elementType = Object.class;
            }
        }
        return resolveManagedArray(argName, (List<?>) value, elementType);
    }
    //5.2解析List
    else if (value instanceof ManagedList) {
        // May need to resolve contained runtime references.
        return resolveManagedList(argName, (List<?>) value);
    }
    // 解析Set
    else if (value instanceof ManagedSet) {
        // May need to resolve contained runtime references.
        return resolveManagedSet(argName, (Set<?>) value);
    }
    // 解析Map
    else if (value instanceof ManagedMap) {
        // May need to resolve contained runtime references.
        return resolveManagedMap(argName, (Map<?, ?>) value);
    }
    // 解析Properties
    else if (value instanceof ManagedProperties) {
        Properties original = (Properties) value;
        Properties copy = new Properties();
        original.forEach((propKey, propValue) -> {
            if (propKey instanceof TypedStringValue) {
                propKey = evaluate((TypedStringValue) propKey);
            }
            if (propValue instanceof TypedStringValue) {
                propValue = evaluate((TypedStringValue) propValue);
            }
            if (propKey == null || propValue == null) {
                throw new BeanCreationException(
                        this.beanDefinition.getResourceDescription(), this.beanName,
                        "Error converting Properties key/value pair for " + argName + ": resolved to null");
            }
            copy.put(propKey, propValue);
        });
        return copy;
    }
    // 解析String
    else if (value instanceof TypedStringValue) {
        // Convert value to target type here.
        TypedStringValue typedStringValue = (TypedStringValue) value;
        Object valueObject = evaluate(typedStringValue);
        try {
            Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
            if (resolvedTargetType != null) {
                return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
            }
            else {
                return valueObject;
            }
        }
        catch (Throwable ex) {
            // Improve the message by showing the context.
            throw new BeanCreationException(
                    this.beanDefinition.getResourceDescription(), this.beanName,
                    "Error converting typed String value for " + argName, ex);
        }
    }
    else if (value instanceof NullBean) {
        return null;
    }
    else {
        return evaluate(value);
    }
}

5.1 解析依賴(lài)

核心還是getBean方法!開(kāi)始觸發(fā)關(guān)聯(lián)創(chuàng)建Bean

private Object resolveReference(Object argName, RuntimeBeanReference ref) {
    try {
        Object bean;
        // 獲取BeanName
        String refName = ref.getBeanName();
        refName = String.valueOf(doEvaluate(refName));
        // 如果Bean在父容器,則去父容器取
        if (ref.isToParent()) {
            if (this.beanFactory.getParentBeanFactory() == null) {
                throw new BeanCreationException(
                        this.beanDefinition.getResourceDescription(), this.beanName,
                        "Can't resolve reference to bean '" + refName +
                                "' in parent factory: no parent factory available");
            }
            bean = this.beanFactory.getParentBeanFactory().getBean(refName);
        }
        else {
            // 在本容器,調(diào)用getBean
            bean = this.beanFactory.getBean(refName);
            this.beanFactory.registerDependentBean(refName, this.beanName);
        }
        if (bean instanceof NullBean) {
            bean = null;
        }
        return bean;
    }
    catch (BeansException ex) {
        throw new BeanCreationException(
                this.beanDefinition.getResourceDescription(), this.beanName,
                "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
    }
}

5.2 解析List

直接把 List 集合塞入屬性中即可。

private List<?> resolveManagedList(Object argName, List<?> ml) {
    List<Object> resolved = new ArrayList<>(ml.size());
    for (int i = 0; i < ml.size(); i++) {
        resolved.add(resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));
    }
    return resolved;
}

以上就是Spring populateBean屬性賦值和自動(dòng)注入的詳細(xì)內(nèi)容,更多關(guān)于Spring populateBean屬性的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java 測(cè)試URL地址是否能正常連接的代碼

    Java 測(cè)試URL地址是否能正常連接的代碼

    本文給大家分享兩段代碼分別是java測(cè)試URL地址是否能正常連接和Java檢測(cè)URL是否可用或者可打開(kāi)的代碼,代碼都很簡(jiǎn)單,有需要的朋友可以參考下
    2016-08-08
  • 關(guān)于Java 并發(fā)的 CAS

    關(guān)于Java 并發(fā)的 CAS

    后端開(kāi)發(fā)鎖成為一個(gè)不可避免的話(huà)題,今天我們討論的是與之對(duì)應(yīng)的無(wú)鎖 CAS。本文會(huì)從怎么來(lái)的、是什么、怎么用、原理分析、遇到的問(wèn)題等不同的角度帶你真正搞懂 CAS。
    2021-09-09
  • springboot使用@data注解減少不必要代碼

    springboot使用@data注解減少不必要代碼

    這篇文章主要介紹了springboot使用@data注解減少不必要代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • 使用Feign設(shè)置Token鑒權(quán)調(diào)用接口

    使用Feign設(shè)置Token鑒權(quán)調(diào)用接口

    這篇文章主要介紹了使用Feign設(shè)置Token鑒權(quán)調(diào)用接口,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Springboot項(xiàng)目接口限流實(shí)現(xiàn)方案

    Springboot項(xiàng)目接口限流實(shí)現(xiàn)方案

    這篇文章主要介紹了Springboot項(xiàng)目接口限流實(shí)現(xiàn)方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • java基礎(chǔ)-給出一個(gè)隨機(jī)字符串,判斷有多少字母?多少數(shù)字?

    java基礎(chǔ)-給出一個(gè)隨機(jī)字符串,判斷有多少字母?多少數(shù)字?

    這篇文章主要介紹了java基礎(chǔ)-給出一個(gè)隨機(jī)字符串,判斷有多少字母?多少數(shù)字?文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • java compare compareTo方法區(qū)別詳解

    java compare compareTo方法區(qū)別詳解

    本文主要介紹了java compare compareTo方法區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Spring Boot的Profile配置詳解

    Spring Boot的Profile配置詳解

    本篇文章主要介紹了Spring Boot的Profile配置詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-05-05
  • Java中Thread類(lèi)基本用法詳解

    Java中Thread類(lèi)基本用法詳解

    Java中的Thread類(lèi)是用于創(chuàng)建和管理線(xiàn)程的類(lèi),Thread類(lèi)提供了許多方法來(lái)管理線(xiàn)程,包括啟動(dòng)線(xiàn)程、中斷線(xiàn)程、暫停線(xiàn)程等,下面這篇文章主要給大家介紹了關(guān)于Java中Thread類(lèi)基本用法的相關(guān)資料,需要的朋友可以參考下
    2023-06-06
  • 使用kafka-console-consumer.sh不停報(bào)WARN的問(wèn)題及解決

    使用kafka-console-consumer.sh不停報(bào)WARN的問(wèn)題及解決

    這篇文章主要介紹了使用kafka-console-consumer.sh不停報(bào)WARN的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03

最新評(píng)論