java - 在 Spring Boot 中具有相同实现的多个 bean
问题描述
我有一种情况,我正在为特定的 bean 使用一种可能的实现,它看起来像这样:
@Configuration
public class MyConfig {
@Autowired
private ApplicationContext context;
@Bean
public SomeInterface someInterface() {
if (this.context.getEnvironment().getProperty("implementation") != null) {
return new ImplementationOne();
} else {
return new ImplementationTwo();
}
}
}
到目前为止,这工作得很好,直到出现新的要求,使用一个额外的接口,目前只ImplementationTwo
提供实现,使用它是没有意义的ImplementationOne
:
@Bean
public SomeOtherInterface someOtherInterface() {
return new ImplementationTwo();
}
我想这会起作用,但我想知道这是否真的有意义,因为在一种情况下,我可以让两个 bean 基本上实例化同一个对象。那有意义吗 ?有没有更好的方法来实现同样的目标?
解决方案
我相信,如果您有单个接口的多个实现,那么您应该使用以下特定的 bean 名称。
这里 implementation1 将是我们在 Interface1 依赖项中创建和注入的主要 bean。
@Primary
@Bean
public Interface1 implementation1() {
return new Implementation2();
}
@Bean
public Interface1 implementation2() {
return new Implementation2();
}
如果我们需要注入 implementation2,我们需要@Resource 注释,如下所示。
@Resource(name="implementation2")
Interface1 implementation2;
推荐阅读
- c++ - 将 CMake 和 vc142 与 boost 一起使用时出现链接错误 LNK1104
- vue.js - 修复 Vue 中的表格宽度,并在文本超出时添加工具提示
- c# - 如何使用 xaml 将内容动态添加到 wpf 应用程序中的富文本框
- python - 从数据框中删除异常值和周围数据
- c# - app.config 中的修改在执行项目时没有反映
- machine-learning - 使用 LSTM Keras 的序列数据进行多类分类不起作用
- python - 从其他 python 脚本更改 PyQt 的 QLabel
- java - 因“方法代码太大”而引发 GSP 异常?
- markdown - 通过 Pandoc 将 Markdown 格式的 Agda 读写到 LaTeX
- perl - 如何从perl中的给定json文件中提取键和值