Home > Back-end >  @Autowire on field vs @Autowired on Construcor
@Autowire on field vs @Autowired on Construcor

Time:10-05

I am developing a SpringBoot application. Can anyone help me understand what is the difference between the below piece of code. I am working on a restful service and I saw constructor being autowired. I can understand its Constructor Injection. Usually I autowire a field. So I am unable to understand the difference between two.

Scenario 1:

 @RestController
 public class SomeServiceController {

 @Autowired 
 private ASerice aService;

 @Autowired
 private BService bService;
}

Scenario 2:

 @RestController
 public class SomeServiceController {

 private ASerice aService;

 private BService bService;

 @Autowired
 public SomeServiceController (AService aService, BService bService)
 {
   this.aService = aService;
   this.bService = bService;

 }
}

CodePudding user response:

The difference is that with the constructor injection, the class SomeServiceController can only be created if with this constructor.

So you could even instantiate the class to test it.

With field injection, this is not possible. To instantiate the class for a test, you must use reflection to set the two private services.

It's highly recommended to use constructor expression.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators

  • Related