Spring Boot @DependsOn Example

1. Introduction

Spring Boot's flexibility allows developers to control the order in which beans are created and initialized. One of the annotations that facilitate this is @DependsOn. This annotation can specify bean dependencies, ensuring that the specified beans are initialized before the bean that uses this annotation. In this blog post, we will illustrate how to use @DependsOn to control bean loading order in Spring Boot.

Key Points:

1. @DependsOn indicates that a bean should be initialized only after the specified beans have been initialized.

2. It can be used to manage startup sequences when one bean depends on another bean being fully initialized.

3. This annotation helps prevent issues caused by dependencies that are not initialized in the correct order.

4. It can be used on any class annotated with @Component, @Service, @Repository, or @Controller and on configuration classes.

5. While @DependsOn can be used to control bean dependencies, Spring usually manages dependencies automatically through its dependency injection feature.

2. Implementation Steps

1. Define multiple Spring beans in your configuration class or with annotations like @Component.

2. Identify the beans that should be initialized first.

3. Add the @DependsOn annotation to the beans that depend on the initialization of other beans.

4. Specify the names of the beans that it should depend on within the @DependsOn annotation.

3. Implementation Example

// Step 1: Create a basic Spring component that other beans depend on
@Component("firstBean")
public class FirstBean {
    public FirstBean() {
        System.out.println("FirstBean initialized");
    }
}

// Step 2: Create another Spring component that depends on the initialization of FirstBean
@Component
@DependsOn("firstBean")
public class SecondBean {
    public SecondBean() {
        System.out.println("SecondBean initialized");
    }
}

// Step 3: Create your main application class to run the Spring Boot application
@SpringBootApplication
public class SpringBootDependsOnApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDependsOnApplication.class, args);
    }
}

Output:

FirstBean initialized
SecondBean initialized

Explanation:

1. @Component("firstBean"): This creates a Spring bean with the name "firstBean".

2. @DependsOn("firstBean"): This ensures that "firstBean" is initialized before "SecondBean".

3. @SpringBootApplication: This annotation marks the application's entry point and also serves as a configuration class.

4. Initialization order: When the application starts, Spring ensures that FirstBean is initialized before SecondBean due to the @DependsOn annotation.

5. Console Output: The output to the console confirms that FirstBean is created before SecondBean.


Comments