Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Spring
Springmedium

Bean scopes in Spring — what does `singleton` vs `prototype` mean?

Tags
#bean#scope#singleton#prototype
Back to categoryPractice quiz

Answer

`singleton` (default) means one bean instance per Spring container. `prototype` means a new instance each time the bean is requested; for web apps you also have request/session scopes.

Advanced answer

Deep dive

A bean scope controls *how many instances* Spring creates and *when*.

  • `singleton` (default): one instance **per ApplicationContext** (not a JVM-wide singleton). Because it can be used by many threads, it should be stateless or thread-safe.
  • `prototype`: a new instance each time the bean is requested, but after creation Spring **does not fully manage its lifecycle** (e.g., destroy callbacks are not invoked automatically).
  • Web scopes (`request`, `session`, `application`, `websocket`) exist in web applications.

Prototype injected into a singleton (common gotcha)

If you inject a prototype bean into a singleton bean, you still get **one instance** at injection time. If you need a fresh instance per use, inject a provider.

Example

@Component
@Scope("prototype")
class TraceId { /* ... */ }

@Service
class OrderService {
  private final ObjectProvider<TraceId> traceId;
  OrderService(ObjectProvider<TraceId> traceId) { this.traceId = traceId; }

  void handle() {
    TraceId id = traceId.getObject(); // fresh instance
  }
}

Common pitfalls

  • Keeping request/user state in a singleton bean.
  • Assuming prototype beans are automatically cleaned up by Spring.
  • Overusing prototype when a method-local object would do.

Related questions

Spring
What do `@Configuration` and `@Bean` do in Spring?
#configuration#bean#spring-core
Spring
What are Bean Scopes?
#bean#scope#lifecycle
Spring
@Component vs @Bean?
#annotation#configuration#bean
JavaScript
What is a closure and a typical use case?
#closures#scope
JavaScript
Explain hoisting in JavaScript. What is hoisted and what is not?
#hoisting#scope#tdz
JavaScript
What are the differences between var, let, and const?
#variables#scope#es6