Prototype 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="prototype">
</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: 0 and Name: null
NOTE:
Here, first object has data but another object is null. It means if we give values to attribute of another object, then it will show like below.
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.setJobSeekerId(1001);
jsObj2.setJobSeekerName("Babu");
jsObj2.display();
}
}
Sample output
Id: 1000 and Name: Heera
Id: 1001 and Name: Babu
Conclusion:
In prototype scope, we will have a new instance for each
getBean()
method called.