A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Singleton Bean Scope Example in Java Spring Framework

Singleton Bean Scope Example

Step 1. Create model class, in which put some attribute and make setter and getter methods for these attribute and also define a method that will be called from main class to get object info.
package com.ps.model;

public class JobSeeker {

       private int jobSeekerId;
       private String jobSeekerName;
      
       public int getJobSeekerId() {
             return jobSeekerId;
       }
       public void setJobSeekerId(int jobSeekerId) {
             this.jobSeekerId = jobSeekerId;
       }
       public String getJobSeekerName() {
             return jobSeekerName;
       }
       public void setJobSeekerName(String jobSeekerName) {
             this.jobSeekerName = jobSeekerName;
       }
      
       public void display()
       {
             System.out.println("Id: "+this.getJobSeekerId()+" and Name: "+this.getJobSeekerName());
       }
      
}

Step 2. Create spring bean configuration file that contains metadata of beans.

<?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.xsd">

    <!-- bean definitions here -->
    <bean id="js" class="com.ps.model.JobSeeker" scope="singleton">
    </bean>

</beans>



Step 3. Create main class from where spring container will initialize the container and all beans objects.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBeanScope {

       public static void main(String[] args) {
            
             //create ctx object
             ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
            
             JobSeeker jsObj=(JobSeeker) ctx.getBean("js");
              jsObj.setJobSeekerId(1000);
              jsObj.setJobSeekerName("Heera");
             jsObj.display();
            
             JobSeeker jsObj2=(JobSeeker) ctx.getBean("js");
             jsObj2.display();
       }

}

Sample output
Id: 1000 and Name: Heera
Id: 1000 and Name: Heera


Conclusion:


In singleton scope, we will have only one instance for each getBean() method called.


LEARN TUTORIALS

.

.