91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

原創001 | 搭上SpringBoot自動注入源碼分析專車

發布時間:2020-06-20 11:43:04 來源:網絡 閱讀:2878 作者:師長學不動了 欄目:編程語言

本系列為SpringBoot深度源碼專車系列,第一篇發車!

原創001 | 搭上SpringBoot自動注入源碼分析專車

專車介紹

該趟專車是開往Spring Boot自動注入原理源碼分析的專車

專車問題

  • Spring Boot何時注入@Autowired標注的屬性?
  • 如果注入類型的Bean存在多個Spring Boot是如何處理的?

專車示例

  • 定義接口
public interface PersonService {

    String hello(String name);
}
  • 定義接口的一個實現
@Service(value = "studentService")
public class StudentServiceImpl implements PersonService {

    @Override
    public String hello(String name) {
        return "[student service] hello " + name;
    }
}
  • 定義接口的另一個實現
@Service(value = "teacherService")
public class TeacherServiceImpl implements PersonService {

    @Override
    public String hello(String name) {
        return "[teacher service] hello " + name;
    }
}
  • 定義控制器
@RestController
public class TestController {

    @Autowired
    private PersonService studentService;

    @Autowired
    private PersonService teacherService;

    @GetMapping("/hello")
    public String hello(@RequestParam(name = "name") String name) {
        return studentService.hello(name) + "=======>" + teacherService.hello(name);
    }
}

以上示例代碼很簡單,創建了一個接口,接口有兩個實現類,然后在控制器中注入實現類,從而完成業務方法的調用。接下來我們就開始對源碼進行分析

專車分析

在分析代碼之前我們先回憶一下操作對象的步驟:

  • 首先我們會實例化一個對象
  • 然后調用對象的set方法來設置對象的屬性

有了上面的基礎知識,接下來就開始揭秘旅程

尋找入口

在分析源碼的時候最關鍵的一步就是尋找程序的入口,有了入口我們就成功了一半,那么如何尋找程序的入口?針對此處的源碼分析,我們可以在TestController類上打一個斷點,然后查看調用鏈
原創001 | 搭上SpringBoot自動注入源碼分析專車

基于調用鏈路,我們看到有一個doCreateBean方法,該方法就是用來創建bean的,也就是我們上面提到的實例化對象部分

實例化Bean

AbstractAutowireCapableBeanFactory#doCreateBean

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

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 創建bean
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    // ...省略部分代碼
    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        // 填充bean,也就是我們上面提到的調用對象的set方法設置對象屬性
        populateBean(beanName, mbd, instanceWrapper);
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    // ...省略部分代碼
    return exposedObject;
}

填充bean

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    // ...省略代碼
    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        // 遍歷所有的后置處理器
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                // 通過斷點分析我們可以得知此處調用的是AutowiredAnnotationBeanPostProcessor#postProcessProperties
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                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;
            }
        }
    }
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    if (pvs != null) {
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

處理屬性

AutowiredAnnotationBeanPostProcessor#postProcessProperties

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    // 查找當前bean需要注入的元數據信息,以TestController為例,那么需要注入的就是studentService和teacherService兩個屬性
    InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
    try {
        // 注入屬性
        metadata.inject(bean, beanName, pvs);
    }
    catch (BeanCreationException ex) {
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
    }
    return pvs;
}

注入屬性 AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject

protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    // 獲取屬性,此處的屬性就是studentService
    Field field = (Field) this.member;
    // 屬性對應的value
    Object value;
    if (this.cached) {
        value = resolvedCachedArgument(beanName, this.cachedFieldValue);
    }
    else {
        DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
        desc.setContainingClass(bean.getClass());
        Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
        Assert.state(beanFactory != null, "No BeanFactory available");
        TypeConverter typeConverter = beanFactory.getTypeConverter();
        try {
            // 解析屬性依賴
            value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
        }
        catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
        }
        synchronized (this) {
            if (!this.cached) {
                if (value != null || this.required) {
                    this.cachedFieldValue = desc;
                    registerDependentBeans(beanName, autowiredBeanNames);
                    if (autowiredBeanNames.size() == 1) {
                        String autowiredBeanName = autowiredBeanNames.iterator().next();
                        if (beanFactory.containsBean(autowiredBeanName) &&
                                beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                            this.cachedFieldValue = new ShortcutDependencyDescriptor(
                                    desc, autowiredBeanName, field.getType());
                        }
                    }
                }
                else {
                    this.cachedFieldValue = null;
                }
                this.cached = true;
            }
        }
    }
    if (value != null) {
        ReflectionUtils.makeAccessible(field);
        // 給屬性設置值,完成注入功能
        field.set(bean, value);
    }
}

解析屬性依賴 DefaultListableBeanFactory#resolveDependency

public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
        @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

    descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
    if (Optional.class == descriptor.getDependencyType()) {
        return createOptionalDependency(descriptor, requestingBeanName);
    }
    else if (ObjectFactory.class == descriptor.getDependencyType() ||
            ObjectProvider.class == descriptor.getDependencyType()) {
        return new DependencyObjectProvider(descriptor, requestingBeanName);
    }
    else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
        return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
    }
    else {
        Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
                descriptor, requestingBeanName);
        if (result == null) {
            // 解析依賴
            result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
        return result;
    }
}

解析屬性依賴 DefaultListableBeanFactory#doResolveDependency

public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
        @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

    InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
    try {
        // ...省略代碼

        // 解析多個Bean,比如Array、List、Map類型,有興趣可以自己查看分析
        Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
        if (multipleBeans != null) {
            return multipleBeans;
        }

        // 根據類型獲取候選對象,針對studentService而言,該屬性的類型為PersonService
        // PersonService有2個實現類,StudentServiceImpl和TeacherServiceImpl
        // 所以此處獲取結果為StudentServiceImpl對象和TeacherServiceImpl對象
        Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
        if (matchingBeans.isEmpty()) {
            if (isRequired(descriptor)) {
                raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
            }
            return null;
        }

        String autowiredBeanName;
        Object instanceCandidate;
        // 重點處理,如果存在多個匹配的bean
        if (matchingBeans.size() > 1) {
            // 從已經匹配的bean中選擇一個符合的bean
            autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
            if (autowiredBeanName == null) {
                // 如果bean必須注入或者存在多個匹配的bean,則拋出異常
                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;
                }
            }
            // 根據bean名稱獲取對應的示例
            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);
    }
}

此處主要根據類型獲取所有匹配的bean,如果匹配的bean有多個,那么最后會選擇一個符合條件的bean名稱,然后將對應的bena實例返回,調用set方法進行進行注入,到此注入的原理本該結束了。但是還是要分析一下Spring Boot是如何選擇出符合條件的bean?

選擇符合條件的bean DefaultListableBeanFactory#determineAutowireCandidate

protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {
    Class<?> requiredType = descriptor.getDependencyType();
    // 如果bean對應的primary屬性為true,則返回bean對應的名稱
    String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
    if (primaryCandidate != null) {
        return primaryCandidate;
    }
    // 如果候選bean使用javax.annotation.Priority標注,返回高優先級bean對應的名稱
    String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
    if (priorityCandidate != null) {
        return priorityCandidate;
    }
    // Fallback
    // 如果匹配bean的名稱和需要注入的屬性名稱一致,則返回匹配bean的名稱
    for (Map.Entry<String, Object> entry : candidates.entrySet()) {
        String candidateName = entry.getKey();
        Object beanInstance = entry.getValue();
        if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
                matchesBeanName(candidateName, descriptor.getDependencyName())) {
            return candidateName;
        }
    }
    return null;
}

獲取符合條件bean名稱總結:

  • 依據Bean的primary屬性
  • 依據javax.annotation.Priority
  • 依據注入屬性的名稱

專車總結

  • Bean實例化完成后,填充Bean
  • 調用AutowiredAnnotationBeanPostProcessor#postProcessProperties處理屬性
  • 獲取所有需要注入的屬性
  • 根據注入屬性的類型從IOC容器中查找匹配實例
  • 如果匹配實例存在多個,根據primary屬性--->javax.annotation.Priority注解--->注入屬性名稱依次過濾,返回符合條件的Bean名稱
  • 過濾之后,存在一個符合條件的Bean名稱,則返回對應的實例,否則拋出異常

專車回顧

回顧一下開頭的2個問題:

  • Spring Boot何時注入@Autowired標注的屬性?
  • 如果注入類型的Bean存在多個Spring Boot是如何處理的?

第一個問題:是在Bean實例化后,填充Bean的時候注入@Autowired標注的屬性

第二個問題:如果存在多個類型的Bean,會根據primary--->javax.annotation.Priority--->名稱依次過濾,得到最終匹配的bean名稱

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

天祝| 富裕县| 道真| 岱山县| 阳曲县| 仁布县| 江口县| 雅安市| 龙南县| 宕昌县| 晋城| 驻马店市| 阿瓦提县| 渑池县| 新河县| 绥中县| 双流县| 陕西省| 新源县| 民勤县| 清水县| 余庆县| 南澳县| 扶绥县| 新宁县| 长汀县| 陈巴尔虎旗| 丽水市| 石河子市| 安岳县| 开化县| 米脂县| 丹巴县| 东方市| 吉首市| 奉贤区| 岚皋县| 慈溪市| 六枝特区| 廊坊市| 渑池县|