java - 用两种可能的实现定义 bean
问题描述
到目前为止,我有一个非常简单的 bean 定义,如下所示:
@Bean
@Conditional(value=ConditionClass.class)
SomeInterface myMethodImpl(){
return new ImplementationOne();
}
但是,我现在遇到了添加了额外的实现类的情况,我们称之为它ImplementationTwo
,需要使用它而不是ImplementationOne
在配置文件中启用该选项时。
所以我需要的是这样的:
@Bean
@Conditional(value=ConditionClass.class)
SomeInterface myMethodImpl(){
return context.getEnvironment().getProperty("optionEnabled") ? new
ImplementationOne() : new ImplementationTwo();
}
基本上是一种在 bean 定义时根据配置值实例化正确实现的方法。这可能吗,有人可以举个例子吗?谢谢
解决方案
可以在不使用@Conditional
.
假设您有一个接口SomeInterface
和两个实现ImplOne
ImplTwo
:
SomeInterface.java
public interface SomeInterface {
void someMethod();
}
ImplOne.java
public class ImplOne implements SomeInterface{
@Override
public void someMethod() {
// do something
}
}
ImplTwo.java
public class ImplTwo implements SomeInterface{
@Override
public void someMethod() {
// do something else
}
}
然后您可以控制在配置类中使用哪个实现,如下所示:
MyConfig.java
@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();
}
}
}
确保 spring 的组件扫描找到MyConfig
. 然后,您可以使用@Autowired
在代码中的其他任何地方注入正确的实现。
推荐阅读
- android - Android Studio CMake 为所有构建变体构建一次
- javascript - 未实现页面之间的Angular 7数据更新
- javascript - 是否可以将具有 2 个以上字段的对象返回到 Redux 中的操作?
- oracle - 无法减去 oracle 形式的变量值
- oracle-data-integrator - CDC ODI - 为什么 odi 需要两个视图 JV$ 和 JV$D
- java - Spring WebFlux 与传统 Web 安全
- android - ConstraintLayout 中未遵守的约束
- java - 如何在多模块 Maven 项目中自动重用依赖版本?
- ms-access - 类别的每月百分比份额,而不是累积的
- scala - 如何为我的 spark 程序选择 scala 版本?