What are the scopes of spring bean?

-->
  • In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.
  • Singleton [Default]
    • Only one instance of bean per spring IOC container
  • Prototype
    • A new instance every time bean is requested
  • Request [Web Application Related]
    • Single bean instance per HTTP request
    • Essentially these are available through web aware application context (e.g. WebApplicationContext)
  • Session [Web Application Related]
    • Single bean instance per HTTP session
    • Essentially these are available through web aware application context (e.g. WebApplicationContext)
  • Global session [Web Application Related]
    • Single bean instance per global HTTP session
    • Essentially these are available through web aware application context (e.g. WebApplicationContext)
    • Global-session is a little different in sense that it is used when application is portlet based. In portlets, there will be many applications inside a big application and a bean with scope of ‘global-session’ will have only one instance for a global user session.

Example – In Bean Configuration File

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="demoBean" class="com.emexo.application.web.DemoBean" scope="session" />

</beans>

Example – Using Annotations

@Service
@Scope("session")
public class DemoBean
{
//Some code
}