Spring Bean Scopes
Although Spring manages the beans for us. However, it also provides five scopes by which we can manage the behavior of our application.
There are five scopes that spring provides to configure a bean :
1. Singleton
2. Prototype
3. Session
4. Request
5. Global
Singleton
Whenever we request Spring to create a bean :
BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("application-context.xml"));
Car car = (Car)applicationContext.getBean("car");
Instead of creating a new object/bean every time, it returns the same object/bean for reuse. In simple words we are using the same object/bean every time we request for a new bean.
NOTE :Singleton scope is the default scope of Spring.
Say, for example we have requested for two 'Car' objects/beans, 'car1' and 'car2' from Spring :
Car car1 = (Car)applicationContext.getBean("car");
Car car2 = (Car)applicationContext.getBean("car");
For the above request, Spring will be creating a single object/bean and 'car1' and 'car2' would refer to that.
The only change we have to make is in the <bean ..> tag of 'application-context.xml'.
<bean name = "car" class = "Car" scope = "singleton">
So, the 'application-context.xml' looks like :
application-context.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<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-3.0.xsd">
<bean name = "car" class = "Car" scope = "singleton">
<property name = "brand" value = "Hyundai"/>
</bean>
</beans>
Prototype
Prototype is just the opposite of singleton. i.e. Every time a bean is requested, a new instance is created and handed over.
Say, for example we have requested for two 'Car' objects/beans, 'car1' and 'car2' from Spring :
Car car1 = (Car)applicationContext.getBean("car");
Car car2 = (Car)applicationContext.getBean("car");
For the above request, Spring will be creating two objects/beans, i.e. 'car1' and 'car2'.
The only change we have to make is in the <bean..> tag of 'application-context.xml'.
<bean name = "car" class = "Car" scope = "prototype">
So, the 'application-context.xml' looks like :
application-context.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<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-3.0.xsd">
<bean name = "car" class = "Car" scope = "singleton">
<property name = "brand" value = "prototype"/>
</bean>
</beans>
Request
It is used in Web Application. The scope of the bean is valid per HTTP request.
Session
Also used in Web Applications. The scope of the bean is valid per HTTP session.