Sub topic 10
Singleton scope
This chapter assumes you know @Component, @Bean and constructor injection, and that you can run a Spring application. It also assumes you have seen the lifecycle phases from earlier chapters.
What singleton means in Spring
Singleton is the default scope. The container creates one instance of a bean definition and hands out that same instance to every consumer. Spring caches it in its singleton registry, so getBean and injection points all return the same object.
This differs from the Gang of Four singleton pattern. Spring's singleton is scoped to the container and to the bean definition, not to the class or the JVM.
| Situation | Number of instances |
|---|---|
| Two injection points for one bean definition in one context | 1 |
| Two bean definitions of the same class, with different names | 2 |
| One bean definition in two separate contexts | 2 |
Seeing it in code
The program below uses two contexts. Each context has its own Greeter, so the comparison between contexts is false.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class AppConfig {
@Bean
Greeter greeter() {
return new Greeter();
}
}
class Greeter {
}
public class SingletonDemo {
public static void main(String[] args) {
Greeter first;
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class)) {
first = ctx.getBean(Greeter.class);
Greeter again = ctx.getBean(Greeter.class);
System.out.println("same context: " + (first == again));
}
try (AnnotationConfigApplicationContext other =
new AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println("other context: " + (first == other.getBean(Greeter.class)));
}
}
}The output is same context: true and then other context: false.
When the instance is created
By default the container creates singletons eagerly. They are built at the end of context refresh, after all bean definitions are registered. A missing dependency or a failing @PostConstruct therefore stops startup instead of failing on the first request. A later chapter covers @Lazy and how it changes this timing.
The container also owns the end of the singleton's life. When you close the context, Spring calls the destruction callbacks (@PreDestroy, DisposableBean.destroy, destroyMethod) on each singleton. This matches the closing of the context in the program above.
Thread safety is your job
Every request thread in a web application shares the same singleton. Spring does not synchronize access to it. A singleton that keeps mutable state in a field is a common source of race conditions.
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.stereotype.Component;
@Component
class VisitCounter {
// Broken: private int count; ++count loses updates under concurrency.
private final AtomicInteger count = new AtomicInteger();
int next() {
return count.incrementAndGet();
}
}Prefer stateless singletons. Keep per-request data in method parameters or local variables. If a bean must hold state for one request or one user, use a narrower scope, which later chapters cover.
Common errors
- Storing request data in a singleton field. One user's data leaks into another user's request.
- Assuming a singleton is created per class. Two
@Beanmethods returning the same type give two instances, and injection by type then becomes ambiguous. - Expecting a fresh object from
getBean. Singleton scope returns the cached instance every time. - Injecting a shorter-lived bean into a singleton and expecting it to refresh. The singleton gets its dependency once, at creation.
Exercise
A @Service class has a private List<String> errors field that each request appends to. The service uses default scope. What goes wrong, and what are two ways to fix it?
Show answer
The service is a singleton, so all request threads share one list. Errors from different requests mix together, and concurrent appends to an ArrayList can corrupt it. Fix it by making the service stateless and returning or passing the errors list as a local variable or method result. Alternatively, move the per-request state into a separate request-scoped bean.