In this post under Spring Core, I will explain with example how to wire two beans annotabed with @Bean annotation using constructor.
For our example lets take the below two bean classes.
Bean1
package package10;
public class Bean1 {
private Bean2 bean2;
public Bean1(Bean2 bean2) {
System.out.println("Hello its Bean1");
this.bean2 = bean2;
}
}
As you can see from the code, when creating “Bean1” instance we also need to pass an instance of “Bean2” as constructor argument.
Now lets see the “Bean2” class structure
Bean2
package package10;
public class Bean2 {
public Bean2() {
System.out.println("Hello its Bean2");
}
}
Now we will see how to wire “Bean1” instance with “Bean2” instance.
Below is the main class for your reference
Main class
1 package package10;
2
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
5 import org.springframework.context.annotation.Bean;
6 import org.springframework.context.annotation.Configuration;
7
8 @Configuration
9 public class Example10 {
10 @Bean
11 public Bean1 bean1() {
12 return new Bean1(bean2());
13 }
14
15 @Bean
16 public Bean2 bean2() {
17 return new Bean2();
18 }
19
20 public static void main(String[] args) {
21 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example10.class);
22 Bean1 bean = applicationContext.getBean("bean1", Bean1.class);
23 }
24 }
In the above main code, “bean1()” method is creating an instance of “Bean1” class and while creating it, it also calls “bean2()” method.
The “Bean2” instance created by “bean2()” method is passed as constructor argument to “Bean1” constructor.
In this way “Bean1” instance is wired with “Bean2” instance.
This approach of wiring beans using constructor is called constructor injection.