Using @DependsOn annotation

In this post under Spring Core, I will explain with example the purpose and how to use the “@DependsOn” annotation.

In an Object Oriented Programming, no object is an island, it depends on other objects to perform their job.

When Spring loads the application context, it creates the beans in following order.

If a bean say “A” depends on bean “B” and “B” is set to “A” through constructor injection, then “B” is created first and then “A”.

But if “B” is set to “A” through setter injection, then “A” and “B” can be created in any order and then “B” is set to “A”.

In case of constructor injection, the Spring makes sure that it creates beans in a particular order but in case of setter injection that order is not maintained.

To enforce that order even in case of setter injection we use “@DependsOn” annotation.

Below is an example

Bean1


package package6;

public class Bean1 {
    Bean2 bean;

    public Bean1() {
        System.out.println("Hello its Bean1");
    }

    public Bean2 getBean() {
        return bean;
    }

    public void setBean(Bean2 bean) {
        this.bean = bean;
    }
}

As you can see in the above code, “Bean1” is dependent on “Bean2” and the dependency is set through setter injection.

Next “Bean2” class structure

Bean2


package package6;

public class Bean2 {
    public Bean2() {
        System.out.println("Hello its Bean2");
    }
}

Below is the main class

Main class


1  package package6;
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  import org.springframework.context.annotation.DependsOn;
8  
9  @Configuration
10 public class Example6 {
11     @Bean
12     @DependsOn("bean2")
13     public Bean1 bean1() {
14         Bean1 bean = new Bean1();
15         bean.setBean(bean2());
16         return bean;
17     }
18     
19     @Bean
20     public Bean2 bean2() {
21         return new Bean2();
22     }
23     public static void main(String[] args) {
24         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example6.class);
25     }
26 }

In above code of main class, from line 11 to 17, I have created a bean definition for “Bean1” and also mentioned that this depends on “Bean2” using “@DependsOn” annotation applied at the method level.

Now as a result “Bean2” is always created first before creating “Bean1”.

In this way, we can use “@DependsOn” annotation.

Below is the output

Output


Hello its Bean2
Hello its Bean1

Leave a Reply