Monday, 17 August 2015

prototype - Bean scope

This bean scope just reverses the behavior of singleton scope and produces a new instance each and every time a bean is requested.

<beans xmlns=""

       <bean id="employee" class="spring.bean.scope.prototype.Employee" scope="prototype"/>
package spring.bean.scope.prototype;

public class Employee {
       private String name;

       public String getName() {
              return name;

       public void setName(String name) {
     = name;
package spring.bean.scope.prototype;
import org.springframework.context.ApplicationContext;

public class TestSingleton {
       public static void main( String[] args )  {

              ApplicationContext context = new ClassPathXmlApplicationContext(
                           new String[] {"spring/bean/scope/prototype/Spring-Customer.xml"});

              Employee custA = context.getBean("employee", Employee.class);

              //retrieve it again
              Employee custB = context.getBean("employee", Employee.class);

              if(custA == custB) {
                     System.out.println("both are same instance : prototype");
              } else {
                     System.out.println("both are different instance : prototype");
Output: both are different instance : prototype

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...