Home > Spring > spring scope prototype example

spring scope prototype example

spring scope prototype example

In Spring, bean scope is used to decide which type of bean instance should be returned from Spring container back to the caller.

If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object each time a request is made for that specific bean. As a general rule, use the prototype scope for all beans with full status and the singleton scope for stateless beans.

To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown in the following code snippet

<!-- To create Multiple object --> 
<bean id="t" class="beans.Test" scope="prototype">

Types of bean scopes supported :

  1. singleton – Return a single bean instance per Spring IoC container
  2. prototype – Return a new bean instance each time when requested
  3. request – Return a single bean instance per HTTP request. 
  4. session – Return a single bean instance per HTTP session. 
  5. globalSession – Return a single bean instance per global HTTP session. 

prototype bean scope example:

We are using Ecplise IDE and some required jars to develop below application.

spring scope prototype example

Ecplise IDE : Ecplise Luna

Jars: Placed below jar in “Referenced Libraries” Folder

  1. commons-logging-1.2
  2. spring-beans-5.0.8.RELEASE
  3. spring-context-5.0.8.RELEASE
  4. spring-core-5.0.8.RELEASE

To create this example, we have created 3 files inside src directory.

  1. spring.xml
  2. Test .java
  3. client.java



	<!-- To create Multiple object -->
	 <bean id="t" class="beans.Test" scope="prototype">

Test .java

package beans;
public class Test 
       System.out.println("Test Constructor");
   public void hello()
     System.out.println("Hello World");


package beans;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Client 
	public static void main(String[] args) 
		//Find xml file
		Resource resource=new ClassPathResource("resources/spring.xml");
		//Load xml into container
		BeanFactory factory =new XmlBeanFactory(resource);
		//Create Object of Test Class with reference of "t"
		Object o=factory.getBean("t");
		Object o1=factory.getBean("t");
		Object o2=factory.getBean("t");
		//Compare object of same class
		System.out.println("Compare object of same class");
		Test t =(Test)o;


Test Constructor
Test Constructor
Test Constructor
Compare object of same class
Hello World

Related Topics:-

You may also like :-
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

Your email address will not be published. Required fields are marked *