在我的最近的Spring Boot项目中,我遇到了涉及两个Bean的情况,Bean1和Bean2。在初始化过程中,我需要Bean2依赖于Bean1。
其中Spring中的 @DependsOn 注解,允许我指定在创建Bean2之前,Spring应确保Bean1已初始化。
在 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();
}
}
在这个例子中
通过此设置,Spring 将确保在应用程序上下文初始化期间“firstBean”在“secondBean”之前初始化。