Spring Bean Lifecycle and Scopes
Implement or sketch code for Spring Bean Lifecycle and Scopes. Explain the logic, complexity, and pros/cons of this approach.
Answers use simple, clear English.
Audio N/AQuick interview answer
Logic: Container creates beans: instantiate → inject → @PostConstruct → use → @PreDestroy. Scopes: singleton (default), prototype, request, session.
Detailed answer
Logic: Container creates beans: instantiate → inject → @PostConstruct → use → @PreDestroy. Scopes: singleton (default), prototype, request, session. Complexity notes included in code section when present. Pros: Consistent lifecycle hooks; easy testing with @SpringBootTest. Cons: Prototype injected into singleton stays single accidental instance unless scoped proxy. 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: Junior.
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.
Code example
@Service
public class CacheWarmup {
private final UserRepo repo;
public CacheWarmup(UserRepo repo) { this.repo = repo; }
@PostConstruct
void warm() {
repo.findTop10Active();
}
}Practice code · java (view only · no execution)
@Service
public class CacheWarmup {
private final UserRepo repo;
public CacheWarmup(UserRepo repo) { this.repo = repo; }
@PostConstruct
void warm() {
repo.findTop10Active();
}
}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?