Spring Prototype Scope

Prototype scope creates a new instance every time a call is made to fetch the bean. property to true, as shown below:

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="prototype">
    <!-- collaborators and configuration for this bean go here -->
<<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="..." class="..." singleton="false">
    <!-- collaborators and configuration for this bean go here -->

Select Maven Project and Add Spring Dependency in pom.xml as described in following article. Click Here

1. Create Source File

Create HelloWorld class having getter and setter methods.

package com.kruders.spring;
public class HelloWorld {
    private String message;
    public String getMessage() {
        return message;
    public void setMessage(String message) {
        this.message = message;

2. Create Bean Configuration File

Write the following code in Spring-Bean.xml

<bean id="helloWorld" class="com.kruders.spring.HelloWorld" scope="prototype">

3. Create TestScope Class

Now Create Test class that contains the code to run the example.

package com.kruders.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestScope {
    public static void main(String[] args) {
          ApplicationContext context = 
                 new ClassPathXmlApplicationContext("Spring-Bean.xml");
          HelloWorld message1 = (HelloWorld) context.getBean("helloWorld");
          message1.setMessage("This is Object 1");
          System.out.println("Message " + message1.getMessage());
          HelloWorld message2 = (HelloWorld) context.getBean("helloWorld");
          System.out.println("Message " + message2.getMessage());

Now when you run the TestScope, second retrieval by object ‘message2‘ will display the null set by object ‘message1‘, as the bean ‘helloWorld‘ is in prototype scope.

The folder structure of the example is shown below in Figure 6.1

Figure 6.1 Figure 6.1

You can download the source code of this example here.

No comments yet.

Leave a Reply