Spring Bean Lifecycle and Scopes
As a Senior engineer, explain Spring Bean Lifecycle and Scopes. What problem does it solve and how would you describe it in an interview?
Answers use simple, clear English.
Quick interview answer
At Senior depth: start with the problem, then mechanism, then a short example. Container creates beans: instantiate → inject → @PostConstruct → use → @PreDestroy.
Detailed answer
At Senior depth: start with the problem, then mechanism, then a short example. Container creates beans: instantiate → inject → @PostConstruct → use → @PreDestroy. Scopes: singleton (default), prototype, request, session. Core: Container creates beans: instantiate → inject → @PostConstruct → use → @PreDestroy. Scopes: singleton (default), prototype, request, session. Real-time example: @Service OrderService injected into @RestController; @PostConstruct loads cache on startup. Pros: Consistent lifecycle hooks; easy testing with @SpringBootTest. Cons: Prototype injected into singleton stays single accidental instance unless scoped proxy. Common mistakes: Calling @Transactional methods via this (self-invocation bypasses proxy). Best practices: Constructor injection for required deps; lazy init only when startup cost high. Audience level: Senior.
Full explanation
Container creates beans: instantiate → inject → @PostConstruct → use → @PreDestroy. Scopes: singleton (default), prototype, request, session.
Real example & use case
@Service OrderService injected into @RestController; @PostConstruct loads cache on startup.
Pros & cons
Pros: Consistent lifecycle hooks; easy testing with @SpringBootTest. Cons: Prototype injected into singleton stays single accidental instance unless scoped proxy.
Common mistakes
Calling @Transactional methods via this (self-invocation bypasses proxy).
Best practices
Constructor injection for required deps; lazy init only when startup cost high.
Follow-up questions
- How would you test Spring Bean Lifecycle and Scopes?
- What metrics prove Spring Bean Lifecycle and Scopes is healthy in prod?
- How does Spring Bean Lifecycle and Scopes change at 10× traffic?