Search code examples
javadependency-injectionsonarqubecdi

Constructor injection vs Field injection


When injecting any services, I have two choices :

Field injection:

 @Inject 
 private MyService myService;

or Constructor injection:

private MyService myService; 

@Inject
public ClassWhereIWantToInject(MyService mySerivce){
    this.myService = myService;
}

Why is Constructor injection better than Field injection?


Solution

  • I found only two disadvantages in the field injection.

    • Hard to inject mocks when the object is under test. (Can be resolved with @InjectMocks from Mockito)

    • Circle dependencies. If bean A depends on bean B and bean B needs bean A. If you have the constructor injection it easy to find it.