In this post under Spring Core, I will show with example, how to use “@Autowired” annotation for constructor injection.
In previous post, I showed how to use “@Autowired” annotation for setter injection.
We call an approach as setter injection, when Spring framework automatically inject dependency to an object by calling the setter method of the object.
Whereas we call an approach as constructor injection, when Spring framework automatically inject dependency by calling dependent object constructor.
The difference between setter and constructor injection, is the timing of injection.
In case of setter injection the dependee object is injected after the dependent object is created, whereas in case of constructor injection, the dependee object is injected while the dependent object is being created.
For our example I will create two bean classes as shown below
Bean1 class
1 package package18;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.stereotype.Component;
5
6 @Component
7 public class Bean1 {
8 private Bean2 bean2;
9
10 public Bean1(@Autowired Bean2 bean2) {
11 this.bean2 = bean2;
12 }
13
14 public Bean2 getBean2() {
15 return bean2;
16 }
17
18 public void setBean2(Bean2 bean2) {
19 this.bean2 = bean2;
20 }
21 }
In the above bean class, I have annotated the class with “@Component” annotation. In its constructor, I am telling Spring framework to automatically inject a bean of class “Bean2”. For that we added annotation “@Autowired” to the constructor parameter. Refer to line 10.
In this way, we can use “@Autowired” annotation for constructor injection.
I have added code for other classes for your references.
Bean2
package package18;
import org.springframework.stereotype.Component;
@Component
public class Bean2 {
}
Below is the main class for your references
Main class
package package18;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "package18")
public class Example18 {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example18.class);
Bean1 bean1 = applicationContext.getBean(Bean1.class);
System.out.println(bean1.getBean2());
}
}
Note getting an instance of “Bean11” class hasn’t been changed.