Springboot中的@DependsOn注解

发布时间:2024年01月12日

在我的最近的Spring Boot项目中,我遇到了涉及两个Bean的情况,Bean1和Bean2。在初始化过程中,我需要Bean2依赖于Bean1。
其中Spring中的 @DependsOn 注解,允许我指定在创建Bean2之前,Spring应确保Bean1已初始化。

@DependsOn注解:

在 Spring Boot 中,您可以使用@DependsOn注解来定义 bean 之间的依赖关系。该注释指定一个 Bean 的初始化取决于一个或多个其他 Bean 的初始化。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
public class MyConfiguration {

    @Bean(name = "firstBean")
    public FirstBean firstBean() {
        // Create and configure your first bean here
        return new FirstBean();
    }

    @Bean(name = "secondBean")
    @DependsOn("firstBean")
    public SecondBean secondBean() {
        // Create and configure your second bean here
        // It will only be created after the initialization of "firstBean"
        return new SecondBean();
    }
}

在这个例子中

  1. 该firstBean方法用 进行注释@Bean,表明它生成一个名为“firstBean”的 bean。
  2. 该secondBean方法用@Bean和进行注释@DependsOn(“firstBean”)。这意味着“secondBean”bean 依赖于“firstBean”bean。

通过此设置,Spring 将确保在应用程序上下文初始化期间“firstBean”在“secondBean”之前初始化。

文章来源:https://blog.csdn.net/Kenard/article/details/135554365
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。