Spring Bean Scopes

Spring Bean Scopes

There are five scopes of a bean in spring:

  1. Singleton: Only one instance of the bean will be created for each container. This is the default scope for a bean. Singleton bean should not have shared instance variables, that may lead data inconsistency.
  2. Prototype: always a new instance is created when context.getBean()method is called.
  3. Request: This is same as prototype scope, however it is used in web applications. A new instance of the bean is created and associated with HTTP request object.
  4. Session: A new bean is created and associated with HTTP session object in the web application.
  5. Global session: This is used to create global session beans for Portlet applications.

Spring Framework is extendable and you can create your own custom scope. However custom scope is created in rare cases existing scopes are enough for an enterprise application. .

Scope can be defined by XML <bean scope="prototype"> tag or @Scope("prototype") annotation.

FAQ

Q: What are the differences between singleton and prototype scope?