In an earlier section, we had an in-depth discussion about the scopes and their use. We also saw how to manage scope according to the requirements in XML. Usually, @Scope is a class-level annotation. However, it can also be used with bean annotation, and can be applied to a method that indicates scope of the instance returned from it.
The following is the code that indicates the use of @Scope:
package com.ch02.scope.annotation; @Component @Scope(scopeName="prototype") public class Customer_Scope { private String cust_name; private int cust_id; @Autowired @Qualifier(value="address") private Address cust_address; public Customer_Scope() { // TODO Auto-generated constructor stub cust_id=10; cust_name="my name"; } //getters and setters }
You can use the following code to check whether a new instance is provided each time or not:
public class TestCustomer_Scope { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext("customer_new.xml"); Customer_Scope customer = (Customer_Scope) context.getBean("customer_Scope"); System.out.println(customer.getCust_name() + " " + customer.getCust_id() + customer.getCust_address()); customer.setCust_name("new name set"); Customer_Scope customer1 = (Customer_Scope) context.getBean("customer_Scope"); System.out.println(customer1.getCust_name() + " " + customer1.getCust_id() + customer1.getCust_address()); System.out.println("after changing name and using prototype scope"); System.out.println(customer.getCust_name() + " " + customer.getCust_id() + customer.getCust_address()); System.out.println(customer1.getCust_name() + " " + customer1.getCust_id()+ customer1.getCust_address()); } }
You can refer to the complete code at--Ch02_Demo_Annotation.