2016-10-03 4 views
2

私は依存性注入にGuiceを使用しています。私はちょっと混乱しています。Guiceの名前付き注射の使用

com.google.inject.name.Namedと(JSR 330?)の2種類のアノテーションがあります。

私は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(愚かな名前、旧来の問題を無視する)は注釈付けされていないため、うまく適合しません。

答えて

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 
関連する問題