Spring Singleton Scope

When you need one and only one instance of a bean, you should set the singleton property to true, as shown below:

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="singleton">
    <!-- collaborators and configuration for this bean go here -->
<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="..." class="..." singleton="true">
    <!-- collaborators and configuration for this bean go here -->

There is a subtle difference between the instance obtained using the Java Singleton pattern and Spring Singleton. Spring Singleton is a singleton per context or container, whereas the Java Singleton is per process and per class loader.

Select Maven Project and Add Spring Dependency in pom.xml as described in following article. Click Here

1. Create Source File

Create HelloWorld class having getter and setter methods.

package com.kruders.spring;
public class HelloWorld {
    private String message;
    public String getMessage() {
        return message;
    public void setMessage(String message) {
        this.message = message;

2. Create Bean Configuration File

Write the following code in Spring-Bean.xml to ensure that only one instance of a bean is created.

<bean id="helloWorld" class="com.kruders.spring.HelloWorld" scope="singleton">

3. Create TestScope Class

Now Create Test class that contains the code to run the example.

package com.kruders.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestScope {
    public static void main(String[] args) {
          ApplicationContext context = 
                 new ClassPathXmlApplicationContext("Spring-Bean.xml");
          HelloWorld message1 = (HelloWorld) context.getBean("helloWorld");
          message1.setMessage("This is Object 1");
          System.out.println("Message " + message1.getMessage());
          HelloWorld message2 = (HelloWorld) context.getBean("helloWorld");
          System.out.println("Message " + message2.getMessage());

Now when you run the TestScope, second retrieval by object ‘message2‘ will display the message set by object ‘message1‘, as the bean ‘helloWorld‘ is in singleton scope.

The folder structure of the example is shown below in Figure 5.1

Figure 5.1 Figure 5.1

You can download the source code of this example here.

No comments yet.

Leave a Reply