如果我在 spring 中有多个配置文件,bean 加载的顺序是什么?
what is the order of bean loading if I have multiple configuration files in spring?
我在 spring 应用程序中有三个配置文件。
@Configuration
public class FooConfig { ... }
@Configuration
public class BarConfig { ... }
@Configuration
public class FooBarConfig { ... }
bean 的加载顺序是什么?我可以在 BarConfig
中使用 FooConfig
中定义的 bean
吗?
编辑
这可以正常工作。但我怀疑它是否因为偶然而起作用。这里存在歧义,因为使用了不同的配置文件,并且解析它们的顺序对于正确加载 bean 很重要。
您可以使用依赖注入 @Autowired
来引用在其他 java 配置 类 上声明的 bean,但仍然无法确定自动装配的 bean 定义的确切声明位置和解决方案是使用 @Import
@Configuration
@Import({FooConfig.class, FooBarConfig .class})
public class FooBarConfig {
//use Autowire to import bean declared in both FooConfig and FooBarConfig
}
编辑:
至于 bean A 依赖于 bean B 的顺序,你保证 B 将在 A 之前实例化,如果没有依赖注入来维护这个命令,或者解决方法是使用 [=13= 注入未使用的依赖项].
我在 spring 应用程序中有三个配置文件。
@Configuration
public class FooConfig { ... }
@Configuration
public class BarConfig { ... }
@Configuration
public class FooBarConfig { ... }
bean 的加载顺序是什么?我可以在 BarConfig
中使用 FooConfig
中定义的 bean
吗?
编辑
这可以正常工作。但我怀疑它是否因为偶然而起作用。这里存在歧义,因为使用了不同的配置文件,并且解析它们的顺序对于正确加载 bean 很重要。
您可以使用依赖注入 @Autowired
来引用在其他 java 配置 类 上声明的 bean,但仍然无法确定自动装配的 bean 定义的确切声明位置和解决方案是使用 @Import
@Configuration
@Import({FooConfig.class, FooBarConfig .class})
public class FooBarConfig {
//use Autowire to import bean declared in both FooConfig and FooBarConfig
}
编辑: 至于 bean A 依赖于 bean B 的顺序,你保证 B 将在 A 之前实例化,如果没有依赖注入来维护这个命令,或者解决方法是使用 [=13= 注入未使用的依赖项].