Spring Bean Scopes

With a simple Spring annotation you get the flexibility to choose the scope of a bean definition and objects created for a particular bean definition.

The scope of a bean defines the lifecycle and visibility of a bean inside a given context. In case of Spring Framework we have the following types:

  • Singleton
  • Prototype
  • Request
  • Session
  • Application
  • Websocket

Singleton

It’s the default scope, the container will create a single instance of a bean and every request for this bean will return the same object which is cached. This scope reaches only the ApplicationContext.

@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)

Prototype

In this case the container will create a new object each time a request is made to this bean. It’s mostly used when we need to maintain state.

@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)

Request

In this case a new bean is created for each HTTP request that is made. It’s mostly used in authentication and authorization context.

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)

Session

In this case only one bean will be created for each HTTP session

@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)

Application

In this case a bean will be created for all the lifecycle of the ServletContext.

@Bean
@Scope(
  value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)

Websocket

In this case the bean will be alive while the websocket session remains.

@Bean
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)

References:

https://www.baeldung.com/spring-bean-scopes

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html

Leave a comment