在Guice中使用命名注入

时间:2016-10-03 11:34:27

标签: java dependency-injection 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")之类的内容,但是当我需要com.google.inject.name.Named中的javax.inject时,我会返回CustomerTypeProviderProvider.class.getAnnotation(javax.inject.Named.class)

CustomerTypeProviderProvider也不合适,因为{{1}}(忽略愚蠢的名称,遗留问题)没有注释。

1 个答案:

答案 0 :(得分:4)

如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