Guice重写NamedCache绑定

问题描述 投票:1回答:1

我正在使用Play 2.6和Play缓存抽象。

我在应用程序中配置了2个缓存,名称为“x”和“y”。

在测试期间,我想用我的假缓存实现覆盖每个缓存。

缓存用@NamedCache("X") val cache: AsyncCacheApi@NamedCache("Y") val cache: AsyncCacheApi注释,但我似乎无法在模块中覆盖它们:

    class FakeCacheModule extends AbstractModule {
      override def configure(): Unit = {
        bind(classOf[AsyncCacheApi]).annotatedWith(Names.named("X")).toInstance(new FakeCache)
        bind(classOf[AsyncCacheApi]).toInstance(new FakeCache)
        bind(classOf[AsyncCacheApi]).annotatedWith(Names.named("Y")).toInstance(new FakeCache)
      }
    }

这些绑定都不起作用。

playframework guice ehcache
1个回答
0
投票

Names.named("")返回com.google.inject.name.Named的实例,但缓存绑定用play.cache.NamedCache注释。

Names.named()的实施是:

public static Named named(String name) {
    return new NamedImpl(name);
}

并且你可以通过使用NamedCache的实例来获得NamedCacheImpl注释的工作绑定,它实现了NamedCache。因此,一个有效的解决方案

class FakeCacheModule extends AbstractModule {
    override def configure(): Unit = {
        bind(classOf[AsyncCacheApi]).annotatedWith(new NamedCacheImpl("X")).toInstance(new FakeCache)
        bind(classOf[AsyncCacheApi]).toInstance(new FakeCache)
        bind(classOf[AsyncCacheApi]).annotatedWith(new NamedCacheImpl("Y")).toInstance(new FakeCache)
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.