Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor injection vs Field injection [duplicate]

Tags:

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?

like image 708
Riadh Avatar asked Nov 22 '16 09:11

Riadh


People also ask

What is the difference between constructor injection and 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.

Which is better constructor or field injection?

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.

Why constructor injection is preferred over field injection?

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.

What is the difference between constructor injection and setter injection?

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.


1 Answers

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.

like image 132
dehasi Avatar answered Oct 16 '22 23:10

dehasi