Configuration Based Autowiring Example in Spring

Tuesday, June 8, 2010

In the last post I showed how annotations can be used for autowiring. In this example I will show how you can used configuration file(xml) based autowiring. I am taking the exact scenario as in last example but moving the control of autowiring from Java to the coniguration file.

For this we need to change only two file and I am sharing the code for this two file.

1. Customer.java. We remove the annotation declaration. Remember that even if the annotation is present it will not make any difference. When ever autowiring is configured from both Java and XML, XML autowiring is applied later and therefore overwrites the Java based configurations.


package headfirstspring;

public class Customer {

private Address address;
private Identity identity;

public Customer(Identity identity, Address address) {
this.address = address;
this.identity = identity;
}

public String showStateInfo(){
return (identity.getFirstName() + " stays in "+address.getState() + " state.");
}
}


2. config.xml. See how we need to just add one attribute in the Customer bean declaration and that is all we need to do. It really is simple, isn't it?



xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
















Apply these two changes and you are ready to test the program as per the last post since everything else remains the same.

Related Posts
Annotation Based Autowiring Example in Spring

0 comments:

Post a Comment

  © Blogger template On The Road by Ourblogtemplates.com 2009

Back to TOP