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?
Constructor Injection: State Safe. The object is instantiated to a full state or is not instantiated at all. Field Injection: Consumer uses no-argument constructor. There is no valid way to set state of the object.
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.
Constructor injection makes code more robust. It allows us to create immutable objects, preventing NullPointerException s and other errors. You can find the code example on GitHub.
Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring's IOC container. On the other hand, constructor injection uses the constructor to inject dependency on any Spring-managed bean.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With