I have a piece of code with field injections I am trying to convert to use constructor injections instead. The initial code looks like this:
@Autowired
private Environment env;
@Autowired
private YYYAdaptor yyyAdaptor;
@Autowired
private JAXBContext jaxbContext;
And this is how I rewrite it:
private Environment env;
private YYYAdaptor yyyAdaptor;
private JAXBContext jaxbContext;
@Autowired
public YYYResource(Environment env, YYYAdaptor yyyAdaptor,
@Qualifier("YYYYReq") JAXBContext jaxbContext) {
this.env = env;
this.yyyAdaptor = yyyAdaptor;
this.jaxbContext = jaxbContext;
}
Doing this gives me a critical vulnerability on the sonar scan, with "this member" referring to each of the declared variables:
Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it
What is the best way I can avoid using field injections while avoiding sonar throwing a fit?
Check-out the SonarQube rule RSPEC-4288: Spring components should use constructor injection. Although it doesn't explain why the final
usage is triggered as non-compliant, there is a compliant code sample. Initialize the fields as null
to make it SonarQube compliant:
private Environment env = null;
private YYYAdaptor yyyAdaptor = null;
private JAXBContext jaxbContext = null;
However, what SonarQube says is not sacred and is filled with lots of false-positives. These static-analyzers hits the issues that are worth the further introspection, yet not definitive and based on the rules made by people with opinions.
Personally, I'd mark this issue as won't fix and declare the fields as final
to make the object immutable:
private final Environment env;
private final YYYAdaptor yyyAdaptor;
private final JAXBContext jaxbContext;