首页 > 解决方案 > 用两种可能的实现定义 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 定义时根据配置值实例化正确实现的方法。这可能吗,有人可以举个例子吗?谢谢

标签: javaspringspring-bootjavabeans

解决方案


可以在不使用@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在代码中的其他任何地方注入正确的实现。


推荐阅读