Autowiring By Bean Type or Bean Name

Thursday, June 10, 2010

In the previous example of autowiring, we saw how autowiring works based on constructor arguments.

Autowiring feature is used to supply property values to bean without explicitly mentioning which bean which will be injected. In this example we will see how autowiring happens by bean type.

Let us say Customer class is dependent on Identity and Address classes. In the previous post we saw how we can inject the dependencies through the constructor using the




In the Customer class we had a constructor like the following…

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

Since we now want to inject the dependency using the bean type, here is how the bean definition will look like in the configuration file.





Here is the Configuration file.





















When we declare autowire="byType" as above, Spring will search for beans whose data type match with the data type of dependencies in Customer class. It finds that there are two beans with ids "identity" and "address" which are declared with matching data type and these are injected in the Customer bean.

Another change will be introducing a default constructor in the Customer class. Otherwise Spring will try to create the bean with the existing constructor and that needs two objects. Since we are now going to use the setter method for the dependency we also added the setter methods.

Here is the code for the Customer class.


package headfirstspring;

public class Customer {

private Address address;
private Identity identity;

public Customer() {
}

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

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

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public Identity getIdentity() {
return identity;
}

public void setIdentity(Identity identity) {
this.identity = identity;
}
}


Remaining code and classes remain the same as the previous example.

Autowiring By Bean Name
If you want to inject the dependency using bean name which is already declared in the configuration file, make the following change in the Customer bean definition.




This will work since the bean id of the Identity and Address beans in the configuration file matches with the property name defined in the Customer class and the bean type also match.

Related Posts
Configuration Based Autowiring Example in Spring
Annotation base Autowiring Example in Spring

0 comments:

Post a Comment

  © Blogger template On The Road by Ourblogtemplates.com 2009

Back to TOP