【问题标题】:How do I correctly bind multiple implementations of the same service?如何正确绑定同一服务的多个实现?
【发布时间】:2015-11-25 16:11:44
【问题描述】:

我有服务类:Service 及其实现:RedisServiceImpl, DBServiceImpl

在我的应用程序中,几乎每个类都必须使用这两个实现来更新字段。我想使用 Guice 来注入这些服务。

class ServiceModule extends AbstractModule with ScalaModule {

    override def configure(): Unit = {
        bind[Service].annotatedWith(Names.named("Redis")).toInstance(new RedisServiceImpl("localhost"))
        bind[Service].annotatedWith(Names.named("DB")).toInstance(new DBServiceImpl("some external host"))
    }
}

这样的问题是,如果我们离开 redis/db,我将不得不搜索所有类并用新名称替换 "Redis"/"DB"。有没有更简单的方法来做到这一点?

我尝试在 ServiceModule 中创建常量,但在尝试将服务注入类时出现以下错误:

Error:(18, 34) annotation argument needs to be a constant; found: modules.ServiceModule.x
          , @Named(ServiceModule.x) redisService: Service
                             ^

这是我要注入的类:

class Poller @Inject()(
        @Named("PollService") pollService: PollService[List[ChannelSftp#LsEntry]]
      , @Named("Redis") redisStatusService: StatusService
      , @Named("DB") dynamoDbStatusService: StatusService
) {
  ... methods ...
}

如果我尝试过:

class Poller @Inject()(
        @Named(ServiceModule.x) pollService: PollService[List[ChannelSftp#LsEntry]]
      , @Named("Redis") redisStatusService: StatusService
      , @Named("DB") dynamoDbStatusService: StatusService
) {
  ... methods ...
}

我收到上面提到的错误。

【问题讨论】:

    标签: scala dependency-injection guice


    【解决方案1】:

    这是问题所在,Poller 不是你的 Guice 模块:

         @Named(ServiceModule.x) pollService: PollService[List[ChannelSftp#LsEntry]]
    

    注解参数必须是常量,如错误消息中所述:

    Error:(18, 34) annotation argument needs to be a constant; found: modules.ServiceModule.x
          , @Named(ServiceModule.x) redisService: Service
    

    您似乎遇到了与此问题相同的问题:Best practice for use constants in scala annotations;尝试制作 ServiceModule.x 最终结果。

    【讨论】:

      【解决方案2】:

      如果我可以建议:重新考虑一下您实现的模式:责任链,可能是访问者或装饰者。它们不同有多少实现被触发(ChoR 在第一次成功时停止等,命令不受限制或具体)。我看到了不同的 Guice 方法来实现不同的模式。

      PS。我不是宗教狂热的设计模式,也不是因为方法名称“next()”或其他原因而引发的圣战。我可能有类似的问题:2/3 数据源:JAR 资源、文件系统、由 Guice 配置的数据库当地决定

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-09
        • 1970-01-01
        相关资源
        最近更新 更多