Constructor injection vs Field injection

2019-06-16 17:40发布

问题:

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 Constructor injection is better than Filed injection ?

回答1:

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.



回答2:

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)

  • Circe 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.



回答3:

Field injection will be performed correctly if the class that contains this injected will be inject by the framework (spring/ejb/cdi), otherwise (the class will be instantiated by the caller using the new operator) it's really a NullPointerException waiting to happen. In this case, it is better to use constructor injection.

We can perform a reliable field injection, when the injection will be made in a class injected by the framework.