What is a Spring Singleton?
December 25, 2025When working with Spring, you often hear that beans are Singletons by default. But what does that actually mean, and how is it different from the classic Gang of Four (GoF) Singleton pattern?
Spring Singleton vs. Java Singleton
- Java Singleton (GoF): Ensures that one and only one instance of a class exists per ClassLoader.
- Spring Singleton: Ensures that one and only one instance of a bean exists per Spring IoC Container.
If you have multiple containers running in the same JVM, you will have multiple instances of your "Singleton" bean.
Default Scope
By default, every @Bean or @Component you define is a singleton. Spring creates it once during startup and caches it.
@Component
public class UserService {
// This constructor is called only once by Spring
public UserService() {
System.out.println("UserService initialized!");
}
}
Why Spring Uses Singletons
- Performance: Creating objects is expensive. Reuse saves memory and CPU.
- Statelessness: Service and Repository layers are typically stateless, making them perfect candidates for singletons.
Providing a Singleton Bean
You don't need to do anything special! It's the default.
@Configuration
public class AppConfig {
// Explicitly a singleton (default)
@Bean
@Scope("singleton")
public MyService myService() {
return new MyServiceImpl();
}
}
Thread Safety Warning
Since a single instance is shared across multiple threads (e.g., multiple HTTP requests), Spring Singleton beans must be stateless.
Bad Practice (Stateful Singleton):
@Service
public class TicketService {
private int ticketCount = 0; // DANGEROUS! Shared state
public int bookTicket() {
return ++ticketCount; // Race condition heaven
}
}
Good Practice (Stateless):
@Service
public class TicketService {
// State is kept in the database, not in the bean
private final TicketRepository repo;
public TicketService(TicketRepository repo) {
this.repo = repo;
}
public int bookTicket() {
// ... DB operations ...
}
}