Spring - Constructor Injection using Autowiring and Annotations - XML
We have seen Constructor Autowiring using XML. Now, let us see with Annotations.
In the below code we will be writing a constructor in the Car class, which takes the 'Wheel' as a paramenter and initializes it. Let us suppose all our classes are in 'com.learnerslesson' package.
Wheel Class
package com.learnerslesson;
import org.springframework.stereotype.Component;
@Component
class Wheel {
@Value("Solid Tire")
String tireType;
public String getTireType() {
return tireType;
}
public void setTireType(String tireType) {
this.tireType = tireType;
}
}
Car Class
package com.learnerslesson;
import org.springframework.stereotype.Component;
@Component("car")
class Car {
Wheel wheel;
public Car() {
}
@Autowired
public Car(Wheel wheel){
this.wheel = wheel;
}
}
With '@Component("car")', Spring creates a 'Car' bean with name 'car'.
Now, with '@Autowired' annotation above Constructor, Spring searches for a bean of 'Wheel' type. And since the 'Wheel' bean is already there, Spring injects the 'Wheel' bean to the 'Car' class.
Note :This time we have placed the @Autowired annotation above the constructor.
application-context.xml without <bean..> tag
<?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"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.learnerslesson" />
</beans>
In the above xml we have added a few more namespaces for supporting annotation. You can copy the same and paste in your 'application-context.xml'.
Next, we are telling spring that the application has annotations.
<context:annotation-config/>
Also, inform spring that in which package it needs to scan for the annotated classes.
<context:component-scan base-package="com.learnerslesson" />
Assuming our annotated classes are in 'com.learnerslesson' package.
Finally, in the main() method we define our application code to interact with spring.
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("application-context.xml");
Car car = (Car)applicationContext.getBean("car");
System.out.println("The Car tire is : "+car.getWheel().getTireType());
}
}
Output :
The Car tire is : Solid Tire