Bean scopes and lifecycle
Scopes:
singleton(the default): one instance per container. It must be stateless or thread-safe.prototype: a new instance every time one is requested.- Web scopes:
request,sessionandapplication.
The lifecycle of a bean:
- Instantiate it (call the constructor).
- Inject its dependencies.
- Run
BeanPostProcessorhooks, where annotations like@Autowiredare processed. - Call init callbacks:
@PostConstruct,afterPropertiesSet()or@Bean(initMethod = ...). - Wrap it in a proxy if needed (for
@Transactional,@Asyncand other aspects). - Use it.
- On shutdown, call
@PreDestroy(not called for prototype beans).
A prototype inside a singleton
A singleton is created once, so a prototype injected into it is also created only once: every caller shares it. When you need a fresh instance each time, inject ObjectProvider<T> and call getObject(), or use a method annotated with @Lookup. The scopes lab above shows this happening.
@Service
class CheckoutService {
private final ObjectProvider<ShoppingCart> carts; // not the cart itself
CheckoutService(ObjectProvider<ShoppingCart> carts) { this.carts = carts; }
Receipt checkout(List<Item> items) {
ShoppingCart cart = carts.getObject(); // a new prototype every call
items.forEach(cart::add);
return cart.pay();
}
}Lifecycle callbacks
Run code after a bean is fully set up with @PostConstruct (validate configuration, warm a cache) and before shutdown with @PreDestroy (close clients, stop threads). Alternatives: InitializingBean/DisposableBean interfaces, or @Bean(initMethod = "...", destroyMethod = "...") for classes you don't own. Prototype beans are never destroyed by the container: you clean them up yourself.
BeanPostProcessor and BeanFactoryPostProcessor
These are how Spring extends itself. A BeanFactoryPostProcessor changes bean *definitions* before any bean exists (resolving ${...} placeholders, for example). A BeanPostProcessor works on each bean *instance* before and after initialisation: it processes @Autowired and @Value, and it is where proxies for @Transactional, @Async and @Cacheable are created.
Example
@Component
public class CourseCache {
private final Map<Long, Course> cache = new ConcurrentHashMap<>(); // thread-safe
private final CourseRepository repo;
public CourseCache(CourseRepository repo) { this.repo = repo; }
@PostConstruct
void warmUp() { // runs after injection
repo.findTop20ByOrderByRatingDesc().forEach(c -> cache.put(c.getId(), c));
}
@PreDestroy
void shutdown() { cache.clear(); }
}
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class ReportBuilder {
private final List<String> lines = new ArrayList<>();
}Common mistake
Storing per-user data in a field of a singleton @Service. Every request shares it, so users see each other's data.
Under the hood
Injecting a prototype bean into a singleton gives you one prototype instance forever, because injection happens only once. Inject an ObjectProvider<ReportBuilder> and call getObject() each time, or use a @Lookup method. @PostConstruct and @PreDestroy come from jakarta.annotation in Spring 6+.
Check yourself
What is the default Spring bean scope?
How this connects
Know these first
Part of Job-ready backend developer, Spring Core and Spring Security in depth.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.