Open utterances-bot opened 5 months ago
Got to say, this gives me the feeling of "the current state works to well, we need to change something again".
Points:
Field injection is easy to use, we intentionally or unintentionally introduce many dependencies Constructors can also be abused and the caller also needs to know what dependencies the class to be instantiated needs to actually work (violation Single Responsability).
Field injection also has the limitation of not being able to use the @Autowired annotation on fields declared as final/immutable Only valid point for me. Reflection tools however still don't care about final/immutable annotations.
Field injection is not unit test friendly I used Spring in the past and Quarkus currently. As long no DB/Reddis/... dependencies are included Unit tests are fast. Mockito does work really well. If external dependencies are needed Injection vs. Constructor does not make a noticable speed difference (container startup takes much longer).
Final words: Injections makes my life easier, atleast in Java. Can they be abused? Sure. For me long constructors that I need to instantiate in multiple places are worse.
Stop using Field injection in Spring applications - Spring Cloud
Learn the advantages and disadvantages of various Spring injection methods, as well as the limitations of field injection and alternatives.
https://www.springcloud.io/post/2022-08/spring-field-injection/