Spring Bean Lifecycle and Scopes
Design a small subsystem that relies on Spring Bean Lifecycle and Scopes. Outline components, data flow, failure modes, and metrics.
Answers use simple, clear English.
Audio N/AQuick interview answer
Use Spring Bean Lifecycle and Scopes as the core idea. Example shape: @Service OrderService injected into @RestController; @PostConstruct loads cache on startup..
Detailed answer
Use Spring Bean Lifecycle and Scopes as the core idea. Example shape: @Service OrderService injected into @RestController; @PostConstruct loads cache on startup.. Watch for: Prototype injected into singleton stays single accidental instance unless scoped proxy.. Measure success via latency/error/saturation. 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: Fresher.
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?