I have a Servlet that have Spring auto-wiring capabilities using:
WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext())
.getAutowireCapableBeanFactory().autowireBean(this);
When I'm autowiring my beans SonarQube warns with `Servlets should not have mutable instance fields (squid:S2226)
@Autowired
MyBean myBean;
Is it SonarQube bug which ignores Spring autowiring? Can I add different annotation to prevent this warning? am I missing something?
By contract, a servlet container creates one instance of each servlet and then a dedicated thread is attached to each new incoming HTTP request to process the request. So all threads share the servlet instances and by extension their instance fields. To prevent any misunderstanding and unexpected behavior at runtime, all servlet fields should then be either static and/or final, or simply removed.
EDIT
I found similar issue that was fixed about Java's @Inject
that should not raise this warning
In practice when a field is annotated with @Inject it won't be mutated. So fields annotated with this annotation should not raise issue RSPEC-2226.
EDIT 2
Open a potential false positive issue in SonarSource Community