Concept Explanation
A bean is any object Spring creates and manages for you. Understanding how many exist and when they are created explains most confusing Spring behaviour.
Scopes
| Scope | Instances | Use for |
|---|---|---|
singleton | one per container (default) | services, repositories |
prototype | a new one per injection | stateful helpers |
request | one per HTTP request | request-scoped data |
session | one per user session | per-user state |
@Service // singleton by default
public class PricingService { }
@Service
@Scope("prototype") // new instance every time it is asked for
public class ReportBuilder { }
The critical consequence: because services are singletons shared across all request threads, a mutable field on a service is a concurrency bug.
@Service
public class BadCounter {
private int count = 0; // shared by every thread!
public void hit() { count++; } // race condition
}
Keep beans stateless, or guard state with an AtomicInteger or a lock.
Lifecycle Hooks
@Service
public class CacheWarmer {
private final ProductRepository repo;
public CacheWarmer(ProductRepository repo) { // 1. constructor injection
this.repo = repo;
}
@PostConstruct
public void warm() { // 2. after injection completes
System.out.println("Preloading cache...");
}
@PreDestroy
public void flush() { // 3. before shutdown
System.out.println("Flushing cache...");
}
}
Order: constructor → dependency injection → @PostConstruct → bean in use → @PreDestroy.
Note that @PreDestroy does not run for prototype beans — Spring hands them over and forgets them.
Common Mistakes
- Mutable singleton state: The most frequent production bug in Spring apps.
- Work in the constructor: Database calls belong in
@PostConstruct; at constructor time dependencies may not be ready. - Injecting a prototype into a singleton: You get exactly one prototype instance, captured forever. Inject an
ObjectProviderinstead. - Field injection:
@Autowiredon a field hides dependencies and blocksfinal. Prefer constructor injection.
Best Practices
- Constructor injection always: Dependencies become explicit,
final, and trivially testable without Spring. - Default to stateless singletons: Reach for another scope only with a concrete reason.
- Keep
@PostConstructfast: It runs during startup and delays readiness.
Practice Exercises
- The Instance Count: Create a singleton and a prototype bean that print in their constructors. Inject each three times and count the printouts.
- The Race: Build the
BadCounterabove, hit it from 100 threads, and observe the count falling short of 100. Fix it withAtomicInteger. - The Lifecycle Trace: Add
@PostConstructand@PreDestroylogging to a bean and record the exact order relative to the constructor.