自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

終于有人把Autowired注解講清楚了,贊?。?!

開(kāi)發(fā) 前端
Spring 容器會(huì)自動(dòng)解析構(gòu)造函數(shù)的參數(shù)類型,并為這些參數(shù)找到與其類型匹配的 Bean 實(shí)例,然后注入到構(gòu)造函數(shù)中。

@Autowired是什么

@Autowired 注解由 Spring 的 org.springframework.beans.factory.annotation.Autowired 類定義, 直譯過(guò)來(lái)就是自動(dòng)注入的意思。

@Autowired的定義如下:

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}

@Autowired 的使用場(chǎng)景

1.字段注入

將 @Autowired 直接應(yīng)用于類的成員變量上。Spring 容器會(huì)自動(dòng)為這些變量找到與其類型匹配的 Bean 實(shí)例,并進(jìn)行注入。

public class MyClass {
    @Autowired
    private MyService myService;
}

2.構(gòu)造器注入

將 @Autowired 應(yīng)用于類的構(gòu)造函數(shù)上。

Spring 容器會(huì)自動(dòng)解析構(gòu)造函數(shù)的參數(shù)類型,并為這些參數(shù)找到與其類型匹配的 Bean 實(shí)例,然后注入到構(gòu)造函數(shù)中。

public class MyClass {
    private MyService myService;
    
    @Autowired
    public MyClass(MyService myService) {
        this.myService = myService;
    }
}

3.方法注入

將 @Autowired 應(yīng)用于類的方法上。

當(dāng)類實(shí)例化時(shí),Spring 容器會(huì)自動(dòng)解析這些方法的參數(shù)類型,并為這些參數(shù)找到與其類型匹配的 Bean 實(shí)例,然后調(diào)用這些方法并注入?yún)?shù)。

public class MyClass {
    private MyService myService;

    @Autowired
    public void setMyService(MyService myService) {
        this.myService = myService;
    }
}

需要注意的是,通過(guò) @Autowired 注解實(shí)現(xiàn)依賴注入時(shí),如果在 Spring 容器中找不到與某個(gè)依賴類型匹配的 Bean 實(shí)例(或者找到多個(gè),但沒(méi)有明確的優(yōu)先級(jí)),那么 Spring 將拋出異常。

除非將該注解的 required 屬性設(shè)置為 false,這樣在找不到匹配的 Bean 時(shí),框架將不會(huì)拋出異常。

public class MyClass {
    @Autowired(required = false)
    private MyService myService;
}

@Autowired是如何工作的

在 Spring 中,AutowiredAnnotationBeanPostProcessor (AABP) 負(fù)責(zé)處理帶有 @Autowired 注解的成員變量、Setter 方法。

以下是 AABP 解析 @Autowired 的完整代碼調(diào)用流程:

當(dāng) Spring 容器實(shí)例化一個(gè) Bean 時(shí),會(huì)創(chuàng)建相應(yīng)的 BeanDefinition 對(duì)象。BeanDefinition 包含了關(guān)于 Bean 的所有元數(shù)據(jù)信息。

在容器實(shí)例化、配置和初始化 Bean 的過(guò)程中,它會(huì)調(diào)用 AABP 的 postProcessMergedBeanDefinition 方法,以收集與依賴注入相關(guān)的元數(shù)據(jù)。

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
  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;
 }

findAutowiringMetadata 方法會(huì)查找 Bean 的所有@Autowired 注解相關(guān)的元數(shù)據(jù),并獲取 InjectionMetadata 對(duì)象, 如果該對(duì)象尚不存在,會(huì)創(chuàng)建一個(gè)新的對(duì)象。

protected InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
    // ... (省略無(wú)關(guān)代碼)

    List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
    Class<?> targetClass = clazz;

    // 遍歷 Bean 的類結(jié)構(gòu),從子類向基類查找有@Autowired 注解的字段、方法和構(gòu)造器
    do {
        final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

        ReflectionUtils.doWithLocalFields(targetClass, field -> {
            // 尋找?guī)в蠤Autowired 注解的字段
            MergedAnnotation<?> ann = findAutowiredAnnotation(field);
            if (ann != null) {
                if (Modifier.isStatic(field.getModifiers())) {
                    // 靜態(tài)字段不能自動(dòng)注入
                    // ... (省略錯(cuò)誤處理和日志)
                }
                boolean required = determineRequiredStatus(ann);
                // AutowiredFieldElement 屬性Autowired元素
                currElements.add(new AutowiredFieldElement(field, required));
            }
        });

        ReflectionUtils.doWithLocalMethods(targetClass, method -> {
            // 尋找?guī)в蠤Autowired 注解的Setter方法或普通方法
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                return;
            }
            MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
            if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (Modifier.isStatic(method.getModifiers())) {
                    // 靜態(tài)方法不能自動(dòng)注入
                    // ... (省略錯(cuò)誤處理和日志)
                }
                PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                boolean required = determineRequiredStatus(ann);
                // AutowiredMethodElement 方法 Autowired 元素
                currElements.add(new AutowiredMethodElement(method, required, pd));
            }
        });

        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    }
    while (targetClass != null && targetClass != Object.class);

    // 構(gòu)建并返回 InjectionMetadata 對(duì)象
    return new InjectionMetadata(clazz, elements);
}

上面的代碼中,我在關(guān)鍵位置添加了注釋,老鐵們可以仔細(xì)看一下,上述代碼的主要作用就是找到一個(gè)類中:

  • 添加了@Autowired的屬性信息,用 AutowiredFieldElement進(jìn)行表示。
  • 添加了 @Autowired 的方法信息,用AutowiredMethodElement進(jìn)行表示。

當(dāng)依賴注入需要發(fā)生時(shí),容器會(huì)調(diào)用 AABP 的 postProcessProperties 方法。

該方法中會(huì)調(diào)用 InjectionMetadata 的 inject 方法來(lái)實(shí)際注入 @Autowired 注解的成員變量、成員方法:

metadata.inject(bean, beanName, pvs);

最后,通過(guò)執(zhí)行 AutowiredFieldElement 和 AutowiredMethodElement 的 inject 方法來(lái)實(shí)際注入屬性值和方法參數(shù)。

AutowiredFieldElement 的 inject 方法實(shí)現(xiàn)如下:

@Override
  protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
   Field field = (Field) this.member;
   Object value;
   if (this.cached) {
    try {
     value = resolvedCachedArgument(beanName, this.cachedFieldValue);
    }
    catch (NoSuchBeanDefinitionException ex) {
     // Unexpected removal of target bean for cached argument -> re-resolve
     value = resolveFieldValue(field, bean, beanName);
    }
   }
   else {
    value = resolveFieldValue(field, bean, beanName);
   }
   if (value != null) {
    ReflectionUtils.makeAccessible(field);
    field.set(bean, value);
   }
  }

AutowiredMethodElement 的 inject 方法的實(shí)現(xiàn)如下:

@Override
  protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
   if (checkPropertySkipping(pvs)) {
    return;
   }
   Method method = (Method) this.member;
   Object[] arguments;
   if (this.cached) {
    try {
     arguments = resolveCachedArguments(beanName);
    }
    catch (NoSuchBeanDefinitionException ex) {
     // Unexpected removal of target bean for cached argument -> re-resolve
     arguments = resolveMethodArguments(method, bean, beanName);
    }
   }
   else {
    arguments = resolveMethodArguments(method, bean, beanName);
   }
   if (arguments != null) {
    try {
     ReflectionUtils.makeAccessible(method);
     method.invoke(bean, arguments);
    }
    catch (InvocationTargetException ex) {
     throw ex.getTargetException();
    }
   }
  }

通過(guò)以上流程,AutowiredAnnotationBeanPostProcessor 將解析并注入帶有 @Autowired 注解的成員變量、方法。

責(zé)任編輯:武曉燕 來(lái)源: 小李哥編程
相關(guān)推薦

2020-07-29 09:21:34

Docker集群部署隔離環(huán)境

2021-07-05 22:22:24

協(xié)議MQTT

2019-07-07 08:18:10

MySQL索引數(shù)據(jù)庫(kù)

2021-04-10 10:37:04

OSITCP互聯(lián)網(wǎng)

2020-12-24 15:18:27

大數(shù)據(jù)數(shù)據(jù)分析

2023-08-14 11:35:16

流程式轉(zhuǎn)化率數(shù)據(jù)指標(biāo)

2024-02-23 08:08:21

2019-05-22 08:43:45

指令集RISC-V開(kāi)源

2022-01-05 09:27:24

讀擴(kuò)散寫擴(kuò)散feed

2020-10-16 17:20:21

索引MySQL數(shù)據(jù)庫(kù)

2021-01-29 10:50:04

數(shù)據(jù)中臺(tái)數(shù)據(jù)數(shù)據(jù)管理

2024-02-27 14:27:16

2020-03-02 15:17:37

云原生CNCF容器

2020-04-23 10:21:57

Linux 網(wǎng)絡(luò)編程 數(shù)據(jù)

2024-07-01 13:45:18

2019-06-19 14:58:38

服務(wù)器負(fù)載均衡客戶端

2019-07-04 09:13:04

中臺(tái)百度團(tuán)隊(duì)

2021-02-25 08:21:38

高可用風(fēng)險(xiǎn)故障

2020-10-29 10:35:53

Nginx架構(gòu)服務(wù)器

2022-07-04 11:27:02

標(biāo)簽數(shù)據(jù)指標(biāo)標(biāo)簽體系
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)