我有一个配置类
@Configuration
public class FooConfig{
@Bean
public FooService fooService() { ... }
@Bean
public AbcService abcService() { ... }
}
该类是在我无法更改的库中定义的。我有一个项目,在很多地方都使用了 FooService
。在我的项目中,我有另一个配置类
@Configuration
@Import({
FooConfig.class,
})
public class BarConfig{
@Autowired AbcService abc;
...
}
此处使用 AbcService
是因为有些服务依赖于该服务,并且这些服务在 BarConfig
中声明。但是,这里没有使用FooService
(它只在 Controller 中使用)
我需要更改 FooService
的实现。我可以在 BarConfig
中定义新的 FooService
bean 吗?它会覆盖通过 FooConfig
导入的已经存在的定义吗?
最佳答案
您可以多次重新定义同一个 bean 名称,spring 容器将采用为给定名称处理的最后一个 bean 定义作为获胜者。
在您的情况下,由于包含您无法更改的配置的核心项目不依赖于您在项目中定义的任何 bean,因此如果您重新定义 FooService 它将正常工作
bean 。
之前有很多关于如何覆盖bean定义的答案,你可以看看有更多的信息。
关于java - 覆盖java配置中的bean定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23547482/