Non-Singleton Scope On Spring Stereotype
ID |
java.spring_component_scope_not_singleton |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
best-practice, performance, spring |
Description
Reports @Scope on a @Controller, @RestController, @Service or @Repository class with a value other than "singleton".
Rationale
These four stereotypes are singleton by default: Spring creates exactly one instance for the whole application context. Overriding the scope to "prototype", "request", "session" or similar makes Spring create and destroy a new instance on every matching event instead. The application still behaves correctly — it is not a defect — but in a busy application this is needless churn: extra allocation, extra construction work, and extra garbage for no behavioral gain, since the stereotype’s usual singleton dependencies rarely need per-request state.
@Scope("singleton") on one of these classes is redundant, since it is already the default, but it changes nothing and is not reported. A plain @Component is out of scope — only the four stereotypes above are singleton by default.
// Needless churn - a new instance is created and destroyed per request
@Scope("prototype")
@Service
public class PricingService {
// ...
}
Remediation
Drop @Scope, or set it explicitly to "singleton" if you want to document the default.
// Good - singleton, as it already was by default
@Service
public class PricingService {
// ...
}