代码之家  ›  专栏  ›  技术社区  ›  Zed

在spring boot中实现相同的多个bean

  •  0
  • Zed  · 技术社区  · 7 年前

    我有一种情况,我正在为一个特定的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基本上实例化同一个对象。这有道理吗?有没有更好的方法来实现同样的目标?

    1 回复  |  直到 7 年前
        1
  •  0
  •   janardhan sharma    7 年前

    我相信,如果您有一个接口的多个实现,那么您应该按照下面的方式讨论特定的bean名称。

    在这里,implementation1将是创建和注入的主要bean,在我们有interface1依赖的地方。

    @Primary
    @Bean
    public Interface1 implementation1() {
        return new Implementation2();
    }
    
    @Bean
    public Interface1 implementation2() {
        return new Implementation2();
    }
    

    如果我们需要注入实现2,我们需要@resource注释,如下所示。

    @Resource(name="implementation2")
    Interface1 implementation2;