Using @DependsOn with @Component annotation

In this post under Spring Core, I will show with example how to use “@DependsOn” annotation to indicate dependencies between two beans marked with “@Component” annotation.

For our example we have two beans “Bean1” and “Bean2” and both are annotated with “@Component” annotation.

Now to declare that “Bean2” is dependent on “Bean1”, we annotate the “Bean2” with “@DependsOn” annotation at the class level and pass the “Bean1” name as a parameter to “@DependsOn” annotation
as shown in the below code snippet

Bean1

package package9;

import org.springframework.stereotype.Component;

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

In the above code snippet we have created a bean with name “Bean1”. It is as usual annotated with “@Component” annotation.

Bean2

1  package package9;
2  
3  import org.springframework.context.annotation.DependsOn;
4  import org.springframework.stereotype.Component;
5  
6  @Component
7  @DependsOn("bean1")
8  public class Bean2 {
9      public Bean2() {
10         System.out.println("Hello its Bean2");
11     }
12 }

In the above code snippet, I have created another bean with name “Bean2” and similar to “Bean1” I have annotated with “@Component” annotation.

Next at line 7 I added “@DependsOn” annotation and pass the value “bean1” as parameter to it.

In this way we have created a dependency between “Bean2” and “Bean1”.

As a result of which, whenever Spring tries to create “Bean2” it first creates “Bean1”, if it is not already created.

In this way we can create dependencies between beans annotated with “@Component” annotation.

Leave a Reply