Monday, 17 August 2015

prototype - Bean scope

prototype:
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="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

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

public class Employee {
       private String name;

       public String getName() {
              return name;
       }

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

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...