A bean scope controls how many instances the container creates and how long they live. The lifecycle callbacks let you run code right after a bean is constructed and just before it is destroyed.
A bean scope controls how many instances the container creates and how long they live. The lifecycle callbacks let you run code right after a bean is constructed and just before it is destroyed.
@Service // singleton by default — one shared OrderService for the whole app
public class OrderService { }
@Component
@Scope("prototype") // fresh instance on every getBean/inject
public class ReportBuilder { }
The classic trap: injecting a prototype into a singleton. The singleton is wired once, so it keeps a single prototype instance forever — the "new every time" promise breaks. Fix it with @Lookup, an ObjectProvider<ReportBuilder>, or scoped-proxy.
@Component
public class ConnectionPool {
@PostConstruct // runs after dependencies are injected, before use
public void open() { /* open sockets, warm caches */ }
@PreDestroy // runs on graceful container shutdown (singletons only)
public void close() { /* release resources */ }
}
Important: Spring does not call @PreDestroy on prototype beans — it hands them off and stops tracking them, so you own their cleanup.
This separates people who treat Spring as magic from those who understand the container. The singleton-holding-a-prototype bug is a favorite interview scenario because it is subtle and causes real production bugs. Knowing that singletons must be stateless and thread-safe (they are shared across all request threads) is the practical takeaway interviewers listen for.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate