-
From Sonarqube we have been getting code issues concerning field injection. For example the article here describes it: https://www.baeldung.com/java-spring-field-injection-cons Are some or all of these concerns also valid when using Quarkus field injection? I'm trying to figure out if and when we should use constructor injection instead. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
The concerns in the linked article generally apply to all full-featured dependency injection containers, including CDI. From a purist perspective, constructor injection should obviously be preferred to field injection. On the other hand, field injection is immensely pragmatic (what's the point of writing a constructor that just assigns its parameters to fields?). Specifically when it comes to testing and mocking, Quarkus has multiple tools that make testing a breeze even in presence of field injection (see https://quarkus.io/guides/getting-started-testing). |
Beta Was this translation helpful? Give feedback.
-
For context, sonar-java 7.27.0.33463 added S6813 "Field dependency injection should be avoided". I know nothing about SonarQube, but from my understanding upgrading from SonarQube 9.9 to 10.6 will add that check and therefore cause those using field injection to start getting such warnings. SonarQube 10 seems scheduled to become the "LTA" version this year. There will likely be numerous Quarkus users wondering how to deal with that soon, since Quarkus's documentation implicitly suggests field injection, as can be seen in this prominent example. Moreover, SonarQube's check has It would therefore be quite interesting for Quarkus to take an official stance on this matter, and perhaps provide an opinion about how severe this issue truly is in the context of Quarkus. If the impact is lower as @Ladicek suggests, perhaps SonarQube's check could take that into account. And if the impact truly is medium or higher, then surely Quarkus's documentation should not feature such examples without warnings. Thank you very much for bringing this up @BrianH85 and all others for your contribution |
Beta Was this translation helpful? Give feedback.
The concerns in the linked article generally apply to all full-featured dependency injection containers, including CDI. From a purist perspective, constructor injection should obviously be preferred to field injection. On the other hand, field injection is immensely pragmatic (what's the point of writing a constructor that just assigns its parameters to fields?). Specifically when it comes to testing and mocking, Quarkus has multiple tools that make testing a breeze even in presence of field injection (see https://quarkus.io/guides/getting-started-testing).