Case 1 - Using @Autowired

To discover the beans automatically, Spring provides the @Autowired annotation, which can be used as an alternative to the XML-based configuration with the help of the autowire' attribute. Let's follow the steps to use the @Autowire annotation:

  1. Create a class Customer_Autowired in com.ch02.autowiring.annotation. This is similar to Customer_Component, which we created in stereotype annotations. Don't forget to add a default customer if you don't have one.
  1. Add the @Autowired annotations on the field cust_address as shown in the following code:
@Autowired 
private Address cust_address; 
  1. In customer_new.xml, configure a bean for Address as shown in the following code:
<bean id="cust_address" class="com.ch02.beans.Address"> 
  <property name="build_no" value="2"/> 
  <property name="city_name" value="Pune"/> 
  <property name="pin_code" value="123"/> 
</bean> 
  1. Create TestCustomer_Autowired to get the bean with customer_Autowired as id:
public static void main(String[] args) { 
  // TODO Auto-generated method stub 
  ApplicationContext context = new 
    ClassPathXmlApplicationContext("customer_new.xml"); 
  Customer_Autowired customer = (Customer_Autowired)  
    context.getBean("customer_Autowired"); 
  System.out.println(customer.getCust_name() + "	" + 
    customer.getCust_id() + customer.getCust_address()); 
} 
  1. We will get the following console output on execution:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.38.117