7
@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?

nitinsridar
  • 684
  • 1
  • 12
  • 25
  • Possible duplicate of [What is Dependency Injection and Inversion of Control in Spring Framework?](https://stackoverflow.com/questions/9403155/what-is-dependency-injection-and-inversion-of-control-in-spring-framework) – Nikolai Shevchenko Aug 07 '19 at 04:22
  • 1
    I'm asking how Field Injection works, not What is Ioc or DI? @NikolayShevchenko – nitinsridar Aug 07 '19 at 04:48

1 Answers1

13

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.

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
  • 2
    Yup, It's neither constructor nor setter injection, it's field injection, solves DI by reflection under the hood – nitinsridar Aug 07 '19 at 06:37