Annotation based 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;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
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.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.ps.model" />
</beans>
Step 3. Create main class from where spring container will initialize the container and all beans objects.
package com.ps.model;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBeanScope {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
JobSeeker jsObj=(JobSeeker) ctx.getBean(JobSeeker.class);
jsObj.setJobSeekerId(1000);
jsObj.setJobSeekerName("Heera");
jsObj.display();
JobSeeker jsObj2=(JobSeeker) ctx.getBean(JobSeeker.class);
jsObj2.setJobSeekerId(1001);
jsObj2.setJobSeekerName("Babu");
jsObj2.display();
}
}
Sample output
Id: 1000 and Name: Heera
Id: 1001 and Name: Babu