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:
- 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.
- Add the @Autowired annotations on the field cust_address as shown in the following code:
@Autowired private Address cust_address;
- 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>
- 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()); }
- We will get the following console output on execution: