2013-11-01 40 views
1

我有一個控制器類。GUICE:注入值取決於範圍

這個類需要一個不同的枚舉值,這取決於它被注入的位置。我不想爲控制器創建子類。

我該怎麼做?

例子:

class FirstItem { 

    //some of these have an injected controller which needs the enum value 'FIRST' 
    @Inject 
    @FirstSubItems //Custom annotation for multibinding 
    Set<Item> subItems; 
} 

class SecondItem { 

    //some of these have an injected controller which needs the enum value 'SECOND' 
    @Inject 
    @SecondSubItems //Custom annotation for multibinding 
    Set<Item> subItems; 
} 

class Controller { 
    @Inject 
    MyEnum enumValue; 
} 

可以這樣做優雅?我將如何配置模塊?

模塊看起來像目前這樣:

Multibinder<Item> toolsSectionOne = Multibinder.newSetBinder(binder, Item.class, FirstSubItems.class); 
toolsSectionOne.addBinding().to(Item1.class); 
toolsSectionOne.addBinding().to(Item2.class); 

Multibinder<Item> toolsSectionTwo = Multibinder.newSetBinder(binder, Item.class, SecondSubItems.class); 
toolsSectionTwo.addBinding().to(Item1.class); 
toolsSectionTwo.addBinding().to(Item2.class); 

回答

0

我已經解決了我的問題與PrivateBinder:

Type type = TypeLiteral.get(Item.class).getType(); 
Type setType = Types.setOf(type); 

PrivateBinder privateBinderOne = binder.newPrivateBinder(); 
privateBinderOne.bind(MyEnum.class).toInstance(MyEnum.FIRST); 
Multibinder<Item> toolsSectionOne = Multibinder.newSetBinder(privateBinderOne , Item.class, FirstSubItems.class); 
toolsSectionOne.addBinding().to(Item1.class); 
toolsSectionOne.addBinding().to(Item2.class); 
privateBinderOne.expose(Key.get(setType, FirstSubItems.class)); 

PrivateBinder privateBinderTwo = binder.newPrivateBinder(); 
privateBinderTwo.bind(MyEnum.class).toInstance(MyEnum.SECOND); 
Multibinder<Item> toolsSectionTwo = Multibinder.newSetBinder(privateBinderTwo , Item.class, SecondSubItems.class); 
toolsSectionTwo.addBinding().to(Item1.class); 
toolsSectionTwo.addBinding().to(Item2.class); 
privateBinderTwo.expose(Key.get(setType, SecondSubItems.class)); 

這就像一個魅力。

+0

你可以發佈使用這個類嗎?我需要做類似的事情,不知道你是如何注入這些東西的。 – tom

+0

就像問題中所述(第一段代碼片段)。由於它們是註釋的多重綁定,我通過註釋來注入它們。在構造函數中,它看起來像這樣:@Inject public FirstItem(@FirstSubItems Set )。這對你有幫助嗎?基本上就是在模塊中創建具有自定義配置的子模塊。 – Falcon

+0

歡呼聲,它清除了一點。 – tom