Skip to the page

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.

The 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> and getObject(), a @Lookup method, or a scoped proxy. The simplest fix: it does not need to be a bean; use new or 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 DataAccessException family.
  • @Configuration classes are proxied by default, so calling one @Bean method from another returns the same singleton. proxyBeanMethods = false is 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

  1. What scopes do you know?
  2. Users see lines from other users' reports. Why?
  3. When do you use @Component and when @Bean?
  4. 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 voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview