Thursday, 21 April 2016

How to use Bean scope using Annotations ?


In the configuration XML : 
spring/bean/scope/annotations/Spring-Customer.xml

<beans ...>
   <context:component-scan base-package="spring.bean.scope.annotations" />
</beans>


Bean class with scope annotation
@Service
@Scope("prototype")
public class Employee {
   private String name;

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


Test class
public class Test {
  public static void main( String[] args )  {
     ApplicationContext context 
        new ClassPathXmlApplicationContext( new String[] 
             {"spring/bean/scope/annotations/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


No comments:

Post a Comment

Note: only a member of this blog may post a comment.