在 Guice 中使用命名注入

Using named injection in Guice

我正在使用 Guice 进行依赖项注入,但我有点困惑。不同包中有两个Named注解:

com.google.inject.name.Namedjavax.inject.Named(JSR 330?)。

我渴望依赖javax.inject.*。代码示例:

import javax.inject.Inject;
import javax.inject.Named;

public class MyClass
{
    @Inject
    @Named("APrefix_CustomerTypeProvider")
    private CustomerTypeProvider customerTypeProvider;
}

在我的命名模块中,我可能有以下行:

bind(CustomerTypeProvider.class).annotatedWith(...).toProvider(CustomerTypeProviderProvider.class);

问题:我很好奇我应该在圆点的位置放什么?我希望像 com.google.inject.name.Names.named("APrefix_CustomerTypeProvider") 这样的东西,但是这个 returns com.google.inject.name.Named 而我需要 javax.inject.

中的那个

CustomerTypeProviderProvider.class.getAnnotation(javax.inject.Named.class) 也不太合适,因为 CustomerTypeProviderProvider(忽略愚蠢的名字,遗留问题)没有注释。

如 Guice wiki 所述,both work the same。你不应该为此担心。甚至建议在可用时使用 javax.inject.*,就像您喜欢的那样(同一页底部)。

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.name.Names;
import javax.inject.Inject;

public class Main {
  static class Holder {
    @Inject @javax.inject.Named("foo")
    String javaNamed;
    @Inject @com.google.inject.name.Named("foo")
    String guiceNamed;
  }

  public static void main(String[] args) {
    Holder holder = Guice.createInjector(new AbstractModule(){
      @Override
      protected void configure() {
        // Only one injection, using c.g.i.Names.named("").
        bind(String.class).annotatedWith(Names.named("foo")).toInstance("foo");
      }

    }).getInstance(Holder.class);
    System.out.printf("javax.inject: %s%n", holder.javaNamed);
    System.out.printf("guice: %s%n", holder.guiceNamed);
  }
}

打印:

java.inject: foo
guice: foo