【问题标题】:What is the order of Spring Boot bean creation and dependency injection?Spring Boot bean创建和依赖注入的顺序是什么?
【发布时间】:2019-03-12 21:07:31
【问题描述】:

我正在开发一个使用 Spring Boot 1.5 的项目。它具有以下类型的配置类:

@Configurtion
public class Foo{

 @Autowired
 private DependencyA dependencyA;

 @Bean
 public DependencyA getDependency(){
   return new DependencyAImpl();
  }

}

这在 Spring Boot 1.5 中运行良好,但是当我升级到 Spring Boot 2 时,它不再运行,应用程序无法启动,并出现异常“找不到 DependencyA 类型的 bean”。我认为这可能是因为当 Spring 尝试注入依赖项时没有创建 bean,因此,作为“hack”,将 @Lazy 添加到 dependencyA 注入。这行得通。

鉴于此,配置类的执行顺序是什么。是吗: A)首先创建bean然后注入依赖项 B) 尝试创建具有所有依赖项的实例,然后在配置中创建任何 bean。

【问题讨论】:

    标签: java spring spring-boot dependency-injection spring-config


    【解决方案1】:

    有趣的发现;

    配置类也是 Spring Bean。

    通常首先扫描和实例化配置类。这必须是了解其他配置和 bean 的起点。

    但是你已经添加了@Autowire 来进行字段注入。正如我所说,配置类也是 Spring Bean。因此 spring 需要首先解决它的依赖关系。并陷入死锁。

    回答你的问题。 配置类首先被实例化,在其他 Bean 之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 2018-11-21
      • 1970-01-01
      • 2019-04-03
      相关资源
      最近更新 更多