Spring Boot core · core
Bean scopes, @Component and @Bean
Singletons are shared by all requests and must hold no mutable state. A prototype inside a singleton is created only once. Use @Bean when you control construction.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Scopes: singleton (default, one per context), prototype (new one per lookup), request, session, application, websocket. Web scopes need a web context.
- A singleton is built once, so its prototype dependency is injected once. Every request shares it and its state: users see each other's data.
- A fresh instance each time:
ObjectProvider<ReportBuilder>andgetObject(), a@Lookupmethod, or a scoped proxy. The simplest fix: it does not need to be a bean; usenewor a local variable. - Singletons are thread-safe only when they hold no shared mutable state. Spring does not call @PreDestroy for prototypes.
- @Component (and @Service, @Repository, @Controller) goes on your own classes, found by scanning. @Bean methods are for third-party classes or when you need control over construction.
- @Repository also turns persistence exceptions into Spring's
DataAccessExceptionfamily. - @Configuration classes are proxied by default, so calling one @Bean method from another returns the same singleton.
proxyBeanMethods = falseis lite mode. - Conditional beans:
@Profile("prod"),@ConditionalOnProperty,@ConditionalOnMissingBean(a default that users can replace).
The red pen
Common traps: mistake → fix
Mistake: A prototype bean gives a new object per request
Fix: not when injected into a singleton; it is injected once.
Mistake: Singleton means thread-safe
Fix: only if it has no shared mutable fields.
Mistake: @Bean and @Component are the same
Fix: @Bean is for explicit construction, often of classes you do not own.
Easy to hard
Questions interviewers ask, easy to hard
- What scopes do you know?
- Users see lines from other users' reports. Why?
- When do you use @Component and when @Bean?
- How do you get a fresh object per request inside a singleton?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.