简体   繁体   中英

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

I was working on a project on 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'. 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. 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.

Interesting finding;

A configuration class is also a Spring Bean.

Normally Configuration class gets scanned and instantiated first. This has to be the starting point to know about other configurations and beans.

However you have added @Autowire to do Field Injection. As I said, a configuration class is a Spring Bean too. Hence spring needs to resolve its dependencies first. And got into dead lock.

To answer your question. Configuration Class gets Instantiated First, before other Beans.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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