Spring - Autowiring by Constructor
Autowiring can also be done using Constructor. Let us see with the below example:
In the below code we will be writing a constructor in the Car class, which takes the 'Wheel' as a paramenter and initializes it.
Car Class
class Car {
Wheel wheel;
public Car() {
}
public Car(Wheel wheel){
this.wheel = wheel;
}
}
Wheel Class
class Wheel {
String tireType;
public String getTireType() {
return tireType;
}
public void setTireType(String tireType) {
this.tireType = tireType;
}
}
Now, since the 'Car' class is holding a reference of 'Wheel'. We will define them in 'application-context.xml'.
application-context.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name = "car" class = "Car" autowire="constructor">
<!-- We have commented the below line
<constructor-arg index="0" ref="wheelReference">
-->
</bean>
<bean name = "wheel" class = "Wheel">
<property name = "tireType" value="Thick Tire"/>
</bean>
</beans>
In Constructor Injection without Autowiring we have used the below line
<constructor-arg index="0" ref="wheelReference">
And in this case we have removed it and asked spring to autowire based on constructor
<bean name = "car" class = "Car" autowire="constructor">
Now, Spring goes to the constructor of the 'Car' class and gets the parameter type(which is 'Wheel' in this case).
public Car(Wheel wheel) {
this.wheel = wheel;
}
Then it searches for the bean with class='Wheel' in the 'application-context.xml'.
<bean name = "wheel" class = "Wheel">
It then creates the bean and injects into the constructor of the 'Car' class.