Spring Bean Lifecycle and Scopes
What common mistakes do candidates make around Spring Bean Lifecycle and Scopes, and how do you avoid them?
Answers use simple, clear English.
Audio N/AQuick interview answer
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.
Detailed answer
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. 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: Engineering Manager.
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?