Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Field Injection in Spring Boot works internally?

Tags:

spring-boot

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

like image 308
nitinsridar Avatar asked Aug 07 '19 04:08

nitinsridar


1 Answers

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.

like image 105
Mark Bramnik Avatar answered Sep 25 '22 15:09

Mark Bramnik