How Field Injection in Spring Boot works internall

2020-06-06 05:20发布

问题:

@Autowired
UserService userService;

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

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

回答1:

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

How does it work?

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

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.

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 {
  }

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