Spring Bean Scopes - Singleton
By AmarSivas | | Updated : 2018-01-01 | Viewed : 1213 times

When we define
Spring Bean Scopes
-
1. Singleton
-
2. Prototype
-
3. Request
-
4. Session
-
5. Global Session
One more scope has been introduce in Spring 3.0, which is Thread-scoped.
Singleton
If we define spring bean as singleton, spring container will create the object only once (per container) and it will be cached. And when we request to container to create one more object, the same cached object will be returned. Here same shared object will be maintained and will used for another object' creation request.
We will understand by following example. Please create a maven project as given bellow.

Please create the SpringBean class as given bellow.
/**
*
* @author:AmarSivas
* @since:2017-05-19
*
*/
package com.docsconsole.spring;
public class SpringBean {
public String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Please create the springbeans-config.xml as given bellow.
<?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 id = "springBean" class = "com.docsconsole.spring.SpringBean" scope = "singleton">
</bean>
</beans>
Please execute the TestMainClient and output will be as given follow.
/**
*
* @author:Amar
* @since:2017-05-19
*
*/
package com.docsconsole.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMainClient {
public static void main(String[] args) {
System.out.println("------------Main mehtod has been started here------------------------------");
ApplicationContext context = new ClassPathXmlApplicationContext("com/docsconsole/spring/springbeans-config.xml");
System.out.println("------------ApplicationContext has been created her------------------------");
SpringBean aBean = (SpringBean) context.getBean("springBean");
System.out.println("------------aBean SpringBean object has been created------------------------");
System.out.println("------------SpringBean object hashcode------------------------"+aBean.hashCode());
SpringBean bBean = (SpringBean) context.getBean("springBean");
System.out.println("------------bBean SpringBean object has been created------------------------");
System.out.println("------------SpringBean object hashcode------------------------"+bBean.hashCode());
}
}

If you observe the output we tried to create the SpringBean object two times. But only object has been created, which contains same hashcode.