Constructor injection vs Field injection

Riadh picture Riadh · Nov 22, 2016 · Viewed 14.7k times · Source

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?

Answer

hecko84 picture hecko84 · Nov 22, 2016

Do something like (I assume you are using spring-boot or something comparable for your CDI)

public class ClassWhereIWantToInject{

    private MyService myService; 

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

At this related question there are some valid arguments why to use injection via constructor instead of injection via field. It boils down to the advantage that you can use initialization via constructor also in non-CDI environment i.e. Unit Test, without the need to add more complex logic.