简体   繁体   English

Spring Boot bean创建和依赖注入的顺序是什么?

[英]What is the order of Spring Boot bean creation and dependency injection?

I was working on a project on Spring Boot 1.5. 我当时在Spring Boot 1.5上从事一个项目。 It had the following type of configuration class: 它具有以下类型的配置类:

@Configurtion
public class Foo{

 @Autowired
 private DependencyA dependencyA;

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

}

This worked okay in Spring Boot 1.5, but when I upgraded to Spring Boot 2, this no longer worked, the application would not start up with the exception 'No bean of type DependencyA found'. 在Spring Boot 1.5中可以正常工作,但是当我升级到Spring Boot 2时,它不再起作用,应用程序将无法启动,但出现异常“找不到DependencyA类型的bean”。 I figured that this might be because the bean wasn't created when Spring tried to inject the dependency, and so, as a 'hack', added @Lazy to the dependencyA injection. 我认为这可能是因为在Spring尝试注入依赖项时未创建该Bean,因此,作为“ hack”,在依赖项注入中添加了@Lazy。 This worked. 这很有效。

In light of this, what is the order of execution of a configuration class. 鉴于此,配置类的执行顺序是什么。 Is it: A) First create beans and then inject dependencies B) Try to create instance with all dependencies, and then create any beans in configuration. 是吗:A)首先创建bean,然后注入依赖项B)尝试创建具有所有依赖关系的实例,然后在配置中创建任何bean。

Interesting finding; 有趣的发现;

A configuration class is also a Spring Bean. 配置类也是Spring Bean。

Normally Configuration class gets scanned and instantiated first. 通常,配置类首先被扫描和实例化。 This has to be the starting point to know about other configurations and beans. 这必须是了解其他配置和bean的起点。

However you have added @Autowire to do Field Injection. 但是,您已添加@Autowire进行场注入。 As I said, a configuration class is a Spring Bean too. 如我所说,配置类也是Spring Bean。 Hence spring needs to resolve its dependencies first. 因此,spring需要首先解决其依赖性。 And got into dead lock. 陷入僵局。

To answer your question. 回答你的问题。 Configuration Class gets Instantiated First, before other Beans. 配置类首先在其他Bean之前实例化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM