Wiring together @Bean annotated beans using setter approach

In this post under Spring Core, I will explain with example how to wire two beans annotated with @Bean annotation using setter methods.

For our example lets take the below two classes.

Bean1

package package12;

public class Bean1 {
    private Bean2 bean2;

    public Bean1() {
    }

    public void setBean2(Bean2 bean2) {
        this.bean2 = bean2;
    }

    public void display() {
        System.out.println(this);
        System.out.println(this.bean2);
    }
}

As you can see from the above class structure of “Bean1”, it has setter method to set “Bean2” instance and a “display” method to display the hashcode of the “Bean1” and “Bean2” instances.

Bean2

package package12;

public class Bean2 {
    public Bean2() {
    }
}

The class structure of “Bean2” is very simple.

We haven’t applied any annotations to the above bean classes.

Next we will see the main class

Main Class

1  package package12;
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 Example12 {
10 @Bean
11 public Bean1 bean1() {
12 Bean1 bean1 = new Bean1();
13 bean1.setBean2(bean2());
14 return bean1;
15 }
16
17 @Bean
18 public Bean2 bean2() {
19 return new Bean2();
20 }
21
22 public static void main(String[] args) {
23 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example12.class);
24 Bean1 bean = applicationContext.getBean(Bean1.class);
25 bean.display();
26 }
27 }

In the above main code, “bean1” method, we are creating an instance of “Bean1” at line 12 and then setting its “bean2” property by calling the “setBean2” setter method and to this setter method
we are passing an instance of “Bean2” class. This instance is created by calling “bean2” method. Refer to line 13.

In this way we can use setter methods to wire two beans together.

This approach of wiring beans using setter methods is called setter injection.

Leave a comment