Spring - 多种配置和@CompontentScan 顺序 [英] Spring - multiple configurations and @CompontentScan order
问题描述
我有多个定义 bean 的 Spring @Configuration
类.我运行应用程序的主类有 @SpringBootApplication(scanBasePackageClasses = BasePackage.class)
.
I have multiple Spring @Configuration
classes that define beans. The main class where I run application has @SpringBootApplication(scanBasePackageClasses = BasePackage.class)
.
我的问题是,扫描这些组件和创建 bean 的顺序是什么?
My question, what is the order these components are scanned and beans are created?
@SpringBootApplication(scanBasePackageClasses = BasePackage.class)
public class MyApplication {
public static void main(final String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
和配置
@Configuration
class Config1{
// defines beans
}
@Configuration
class Config2{
// defines beans
}
另一个 maven 依赖也有 Config3
Another maven dependency also has Config3
@Configuration
class Config3{
// defines beans
}
我尝试搜索文档,但没有找到这些组件扫描和初始化的顺序.
I tried to search the documentation, but I did not find which order these components are scanned and initialized.
我问这个问题是因为我有一个带有@ConditionalOnMissingBean 的 bean,以及定义它的多个配置.哪里有官方文档说明,扫描哪个顺序@Configuration
类.
I asked this question because I have a bean that has @ConditionalOnMissingBean, and multiple configurations that define it. Where is in the official documentation statement, which order @Configuration
classes are scanned.
推荐答案
在第一步中,Spring 会扫描与基础包相关的所有类以查找 bean.然后 spring 将创建 bean 并注入它.
In a first step Spring scans all classes relative to your base package for beans. Then spring will create the beans and inject it.
如果您需要按特定顺序创建 bean,您可以添加 @DependsOn
If you need to have the beans created in certain order you can do so by adding @DependsOn
来自文档:
depends-on 属性可以显式强制一个或多个 bean在初始化使用此元素的 bean 之前进行初始化.
The depends-on attribute can explicitly force one or more beans to be initialized before the bean using this element is initialized.
这篇关于Spring - 多种配置和@CompontentScan 顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!