Spring Boot 中的字段注入如何在内部工作? [英] How Field Injection in Spring Boot works internally?

查看:32
本文介绍了Spring Boot 中的字段注入如何在内部工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Autowired
UserService userService;

无论是使用构造函数注入还是Setter注入,在`@Autowired注解内部究竟发生了什么.我知道是场注入.

What happens exactly inside `@Autowired annotation whether it uses Constructor Injection or Setter Injection. I know that it is field Injection.

我不是问 IOC 或 DI 是如何工作的,我是问 Spring Boot 中的字段注入如何在内部工作?

I'm not asking How IOC or DI works, I'm asking How Field Injection in Spring Boot works internally?

推荐答案

基本上字段注入是一种注入(很明显),所以 Spring 根据字段类型和一些注解(比如 @Qualifier).

Basically field inject is a type of injection (obviously), so Spring injects dependency based on field type and maybe some annotations (like @Qualifier).

它是如何工作的?

Spring 创建 bean 时,有一个特殊的 Bean Post Processor org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor

When Spring creates a bean, there is a special Bean Post Processor org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor

@Autowired 标记的每个字段都被 spring 视为一个依赖项,因此它必须分析这些依赖项(通过在后台使用反射)并从应用程序上下文中找到每个字段的匹配项(按类型、限定符(如果指定)等).然后它再次通过反射将值设置到字段中.

Each field marked with @Autowired is considered by spring as a dependency, so it must analyze these dependencies (by using reflection under the hood) and find a match from the application context for each field (by Type, qualifier if specified, etc.). Then it sets the value, right into the field, again by reflection.

我不打算在这里开始holly-wars",但我只想提一下,我个人尽量避免使用这种类型的注入,因为它有效地破坏了依赖项的封装,使具有自动装配字段的类非-单元可测试.例如,如果您有这样的事情:

I don't intend to start "holly-wars" here, but I'll just mention that I personally try to avoid using this type of injection because it effectively breaks encapsulation of dependencies, making the class with autowired fields non-unit testable. For example if you have something like this:

  @Component
  class Foo {
     @Autowired 
     private Bar bar;
     public Foo() {} // no-arg construction that exists by default
  }

  @Component
  class Bar {
  }

然后,当您自己创建 Foo 的实例时(例如在单元测试中),您没有明确的方法将 Bar 依赖项提供给 Foo 不依赖 spring 的实例.

Then when you create an instance of Foo by yourself (e.g. in unit-test) you have no clear way to supply the Bar dependency to Foo instance without relying on spring.

例如,构造函数注入解决了这个问题.

Constructor Injection solves this for example.

这篇关于Spring Boot 中的字段注入如何在内部工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆