Easy java spring

What are bean scopes, and what is the default?

The 30 second answer

The default scope is singleton: one instance per Spring container, shared by everyone who injects it. Prototype creates a new instance every time it is requested. Web apps also have request and session scope, one instance per HTTP request or per user session. Because singletons are shared across threads, a singleton service must not keep per-request data in its fields.

<!-- level: 1 --> <!-- must_know: true -->

The Spring Framework reference lists these scopes:

  • singleton (default): one shared instance per IoC container.
  • prototype: a new instance each time the bean is injected or looked up. Spring does not manage its full lifecycle; destroy callbacks are not called.
  • request, session, application, websocket: web-aware scopes, one instance per HTTP request, per HTTP session, per ServletContext or per WebSocket.
@Component
@Scope("prototype")
public class ReportBuilder { }

The point interviewers check: singleton beans are shared by all request threads, so they should be stateless. Storing the current user or a counter in a field of a @Service is a race condition. Keep per-request data in method variables, the request itself, or a request-scoped bean.

Sources (1)
  1. Spring Framework: Bean scopesdocs.spring.io