Spring Bean Scope

Bean Prototype Scope

A bean declared as prototype in spring will create a new instance for every fresh request.

Declaring a bean as 'prototype' is pretty simple in XML configuration file.

<bean id="..." class="..." scope="prototype">

Spring Prototype Example

Given below is an example of prototype scope.


Java POJO - Student.java

public class Student {
	private String name;
	private String stream;
	//private Subjects subjects;	
	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public String getStream() {
		return stream;

	public void setStream(String stream) {
		this.stream = stream;


XML Configuration - appContext.xml

<?xml version="1.0" encoding="UTF-8"?>  

<bean id="mukeshBean" class="Student" scope="prototype">  


Test class - TestSpringClass.java

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

public class TestSpringClass {

	public static void main(String[] args) {		
		ApplicationContext context = new ClassPathXmlApplicationContext("appContext.xml");
		Student student = (Student) context.getBean("mukeshBean");
		student.setName("Mukesh Tripathi");
		student.setStream("Electronics and Communication");
		System.out.println("::Get Student details::");
		System.out.println(student.getName() +" "+student.getStream());
		Student studentForm = (Student) context.getBean("mukeshBean");
		System.out.println("::Get Form details::");
		System.out.println(studentForm.getName() +" "+studentForm.getStream());



log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
::Get Student details::
Mukesh Tripathi Electronics and Communication
::Get Form details::
null null
Did you notice that studentForm object is printing null as name and stream. Because for this object nothing has been set.
Moreover scope for mukeshBean object is prototype, so this time same instance is not returned as was done in singleton example in last chapter of this tutorial.




Please Share this page
Views : 56
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!