Constructor Injection vs. Field Injection

When entering any services, I have two options:

(Field injection)

@Inject private MyService myService; 

or (constructor injection)

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

Why is a constructor injection better than a filed injection?

+9
source share
4 answers

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; } } 

There are some valid arguments in this related question , why use injection through the constructor instead of injection through the field. This boils down to the fact that you can use initialization through the constructor also in an environment without CDI, that is, Unit Test, without the need to add more complex logic.

+5
source

I found only two flaws in field injections.

  • It is difficult to enter layouts when an object is being tested. (Can be solved using @InjectMocks from Mockito)

  • Circe addiction. If bin A depends on bin B and bean B needs bin A If you have a constructor injector, it is easy to find.

+2
source

The field injection will be executed correctly if the class that contains this injection is implemented by the framework (spring / ejb / cdi), otherwise (the instance will be created by the caller using the new operator), this is really a NullPointerException that is waiting to be thrown. In this case, it is better to use the injection constructor.

We can perform reliable field injection when the injection is in the class introduced by the framework.

0
source

After reading this great post ( https://blog.marcnuri.com/field-injection-is-not-recommended/ ), we can find more detailed explanations of why Field Injection is not a good choice.

This prevents us from making the field immutable using the final keyword.

In addition, this is another step from SRP (the principle of shared responsibility), when a class having this field begins to bear some responsibility for the initialization of third-party classes.

0
source

Source: https://habr.com/ru/post/1260123/


All Articles