繁体   English   中英

使用 Spring 动态注入服务实现

[英]Dynamically inject service implementation with Spring

我已经了解了一些有关如何执行此操作的提示,例如: 堆栈溢出 但我的问题是我自己的实现需要注入其他东西。 这是示例:

public interface MyService {}

public class ServiceImplA implements MyService {

     @Autowired
     private final SomeStuffA a_stuff;

}

public class ServiceImplB implements MyService {

     @Autowired
     private final SomeStuffB b_stuff;

}

@Configuration
public class SpringConfig {

    @Bean
    @Scope("singleton")
    public MyService getService() {
         boolean useA = // read config file and decide impl
         return useA ? new ServiceImplA() : new ServiceImplB();
         // I can't instantiate this, so i need them to be injected as well
    }

}

我熟悉 Google Guice,在那里我会做这样的事情:

bind(MyServicle.class).to(useA ? ServiceImplA.class :  ServiceImplB.class);

所以,我需要一种使用 Spring 来做到这一点的方法

我认为您的问题是您的基类MyService没有标记为任何配置文件。

当您定义配置文件时,具有此类规范的 bean 将覆盖实现相同接口但没有配置文件定义的 bean。 这不是这样工作的。

当使用活动配置文件时, X spring 会启动所有不针对任何配置文件的 bean针对当前配置文件的 bean。 在您的情况下,您可以明智地选择。

我认为如果您想使用配置文件,您应该至少定义 2 个: AB (名称仅作为示例。)

现在将ServiceImplA标记为A并将ServiceImplB标记为B

@Service
@Profile("A") 
public ServiceImplA interface MyService { ... }
and some development implementation

@Service
@Profile("B") 
public ServiceImplB interface MyService { ... }

有关分析的更多信息,您将在here获得

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM