首页 > 解决方案 > 在 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 基本上实例化同一个对象。那有意义吗 ?有没有更好的方法来实现同样的目标?

标签: javaspring-bootjavabeans

解决方案


我相信,如果您有单个接口的多个实现,那么您应该使用以下特定的 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;

推荐阅读