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.
Noncompliant code example
@Controller
public class HelloWorld {
@Autowired
private String name = null; // Noncompliant
}
Compliant solution
As of Spring 4.3
@Controller
public class HelloWorld {
private String name = null;
HelloWorld(String name) {
this.name = name;
}
}
Before Spring 4.3
@Controller
public class HelloWorld {
private String name = null;
@Autowired
HelloWorld(String name) {
this.name = name;
}
}