简体   繁体   English

在 Guice 中使用命名注入

[英]Using named injection in Guice

I'm using Guice for dependency injection and I'm a bit confused.我正在使用 Guice 进行依赖注入,但我有点困惑。 There are two Named annotations in different packages:在不同的包中有两个Named注释:

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

I'm eager to depend on javax.inject.* .我渴望依赖javax.inject.* Code sample:代码示例:

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

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

In my naming module I may have the following line:在我的命名模块中,我可能有以下行:

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

The question: I'm curious what should I put where the dots are?问题:我很好奇我应该把点放在什么地方? I would expect something like com.google.inject.name.Names.named("APrefix_CustomerTypeProvider") but this one returns com.google.inject.name.Named while I need the one in javax.inject .我希望像com.google.inject.name.Names.named("APrefix_CustomerTypeProvider")这样的东西,但是这个返回com.google.inject.name.Named而我需要javax.inject那个。

CustomerTypeProviderProvider.class.getAnnotation(javax.inject.Named.class) also does not fit well because the CustomerTypeProviderProvider (ignore the stupid name, legacy issue) is not annotated. CustomerTypeProviderProvider.class.getAnnotation(javax.inject.Named.class)也不太适合,因为CustomerTypeProviderProvider (忽略愚蠢的名称,遗留问题)没有注释。

As mentioned on the Guice wiki, both work the same .正如在 Guice wiki 上提到的,两者的工作方式相同 You shouldn't worry about that.你不应该担心这个。 It is even recommended to use javax.inject.* when available, just as you prefer too (bottom of the same page).甚至建议在可用时使用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);
  }
}

Prints:印刷:

java.inject: foo
guice: foo

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

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