Beans Scopes in Spring

Spring

Bean scope in Spring are scope for a bean managed by Spring IOC container. As we know that Spring is a framework which is based on Dependency Injection(DI) and Inversion of Control (IoC) and provides bean management facilities to Java application. In Spring managed environment, bean are created and wired by Spring framework. Spring allows you to define how those beans will be created and scope of bean is one of those details.

Spring framework supports five type of scopes and for bean instantiation as of Spring and also we can create a custom scope.

  • Singleton (default) – scopes a single bean definition to a single object instance per Spring IoC container.
  • Prototype – scopes a single bean definition to any number of object instances.
  • Request – scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition.
  • Session – scopes a single bean definition to the lifecycle of a HTTP session.
  • Global-Session – scopes a single bean definition to the lifecycle of a global HTTP session. Typically only valid when used in a portlet context.

Singleton and Prototype are two common bean scope which is available on all Spring application context while RequestSession and Global-Session bean scope are only available on Web-aware application context like WebApplicationContext.

Let say we have POJO class as follow:

Then we create Spring context file for Singleton and Prototype scope.

Example of Singleton

Below is main class for creating Spring application context and get the bean with Singleton scope:

Output:

 

Example of Prototype

Below is main class for creating Spring application context and get the bean with Prototype scope:

Output:

Now you will know what is the different between Singleton and Prototype scope in Spring, right?

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*