【问题标题】:what is the order of bean loading if I have multiple configuration files in spring?如果我在spring中有多个配置文件,bean加载的顺序是什么?
【发布时间】:2015-07-25 03:19:19
【问题描述】:

我在spring应用中有三个配置文件。

@Configuration
public class FooConfig { ... }

@Configuration
public class BarConfig { ... }

@Configuration
public class FooBarConfig { ... }

bean 的加载顺序是什么?我可以在BarConfig 中使用FooConfig 中定义的bean,反之亦然?

编辑

这可以正常工作。但我怀疑它是否因为机会而起作用。这里有一个歧义,因为使用了不同的配置文件,并且解析它们的顺序对于正确加载 bean 很重要。

【问题讨论】:

  • 你尝试的时候发生了什么?
  • @DaveNewton:效果很好。但我怀疑它是否因为机会而运作良好。解析不同的配置文件时存在歧义。

标签: spring spring-mvc dependency-injection spring-annotations


【解决方案1】:

请看spring documentation

您可以使用依赖注入 @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 之前被实例化,如果没有依赖注入来维护该顺序,一个技巧或解决方法是使用 @Resource 注入一个未使用的依赖项。

【讨论】:

  • 我不是在问如何让它工作。我在上面编辑了我的问题。请看一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 2018-01-05
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多