Spring @Controller
, @Service
, and @Repository
classes are singletons by default, meaning only one instance
of the class is ever instantiated in the application. Typically such a class might have a few static
members, such as a logger, but all
non-static members should be managed by Spring and supplied via constructor injection rather than by field injection.
This rule raise an issue when any non-static
member of a Spring component has an injection annotation, or if the constructor of Spring
component does not have injection annotation.
@Controller public class HelloWorld { @Autowired private String name = null; // Noncompliant HelloWorld() { // ... } // ... }
@Controller public class HelloWorld { private String name = null; @Autowired HelloWorld(String name) { this.name = name; // ... } // ... }