×
☰ See All Chapters

Spring Bean Scopes

When we create any spring bean, spring creates objects for those bean declarations. We should define the scope for those objects. By default all the beans are singleton, means single object per application. If required to produce new bean instance each time when bean is used, you should declare the bean's scope attribute to be prototype. We don’t need to declare scope as singleton, because spring by default considers singleton scope for all beans. Spring Framework supports the following five scopes, three of which are available only if you use a web-aware ApplicationContext.

Scope

Description

singleton

Spring container creates only one object for JavaBean class. This single will be used every time whenever the bean is to be injected.

Singleton means one object per JVM.

This is the default scope of a bean. But we can configure explicitly as below.

<bean id="adrress" class="com.java4coding.EmplyeeAdress" scope="singleton"></bean>

prototype

Spring creates new object for each bean consumption.

<bean id="adrress" class="com.java4coding.EmplyeeAdress" scope="prototype"></bean>

request

This is applicable with only Spring web module, when using spring ApplicationContext. A bean configured with this scope will be instantiated for each HHTP request.

<bean id="adrress" class="com.java4coding.EmplyeeAdress" scope="request"></bean>

session

This is applicable with only Spring web module, when using spring ApplicationContext. A bean configured with this scope will be instantiated for each HHTP session.

<bean id="adrress" class="com.java4coding.EmplyeeAdress" scope="session"></bean>

global-session

This is applicable with only portlet applications, when using spring ApplicationContext. A bean configured with this scope will be instantiated for each global session beans for Portlet applications.

<bean id="adrress" class="com.java4coding.EmplyeeAdress" scope=" global-session "></bean>

 


All Chapters
Author