2013-06-07 10 views
5

で複数のオブジェクトをバインドI Guiceのバインディングを使用して、次のコードがあります。私は自分のアプリケーションに注入された両方の名前のFoo秒間Barオブジェクトを取得しようとしているGuiceの:別の依存関係

public class MyApplication { 
    public static void main(String[] args) { 
     Guice.createInjector(new AbstractModule() { 
      @Override 
      protected void configure() { 
       bind(Foo.class).annotatedWith(Names.named("first")).toInstance(new Foo("firstFoo")); 
       bind(Foo.class).annotatedWith(Names.named("second")).toInstance(new Foo("secondFoo")); 

       bind(Bar.class).to(BarImpl.class); 

       bind(MyApplication.class).asEagerSingleton(); 
      } 
     }); 
    } 

    private @Named("first") Bar first; 
    private @Named("second") Bar second; 

    static @Value class Foo { String name; } 
    static interface Bar {} 

    static class BarImpl implements Bar { 
     @Inject @Named Foo foo; 
    } 
} 

を。基本的には、@NamedFooに接続し、Barに接続する必要があります。私は、Providerを書いてすべてに@Namedを入れてから、いくつかの解決策を試しました。私はプロバイダ内の@Named注釈の値にアクセスできないため、後者は機能しませんでした。私は解決策がbind(Bar.class).to(BarImpl.class);のどこかにあり、@Named注釈の値を覚えていると言います。

私の質問は、これはまったく可能ですか?あれば、どうですか?

答えて

10

PrivateModulesを使用しています。基本的に:

プライベートモジュールの設定情報は、デフォルトではその環境から隠されています。明示的に公開されているバインディングのみが、他のモジュールやインジェクタのユーザに利用可能になります。詳細はthis FAQ entryを参照してください。あなたが効果的に

static class BarImpl implements Bar { 
    @Inject Foo foo; 
} 

のように見えるが、PrivateModulesの力で行き異なる実装を持っているそれぞれの2つのバーを持って

protected void configure() { 
    install(new PrivateModule() { 
     @Override 
     protected void configure() { 
      // #bind makes bindings internal to this module unlike using AbstractModule 
      // this binding only applies to bindings inside this module 
      bind(Foo.class).toInstance(new Foo("first")); 
      // Bar's foo dependency will use the preceding binding 
      bind(Bar.class).annotatedWith(Names.named("first")).to(BarImpl.class); 
      // if we'd stop here, this would be useless 
      // but the key method here is #expose 
      // it makes a binding visible outside as if we did AbstractModule#bind 
      // but the binding that is exposed can use "private" bindings 
      // in addition to the inherited bindings    
      expose(Bar.class).annotatedWith(Names.named("first")); 
     } 
    }); 
    install(new PrivateModule() { 
     @Override 
     protected void configure() { 
      bind(Foo.class).toInstance(new Foo("second")); 
      bind(Bar.class).annotatedWith(Names.named("second")).to(BarImpl.class); 
      expose(Bar.class).annotatedWith(Names.named("second")); 
     } 
    }); 
     bind(MyApplication.class).asEagerSingleton(); 
    } 
} 

:ここ

は、あなたがそれを使用したい方法です同じ依存関係。

希望します。

+0

ありがとうございます。これは有望です。私はmondayでそれを試してみるよ。 – Jorn

+1

はい、これは私の問題を解決しました。再度、感謝します! – Jorn

+0

あなたは大歓迎です! –