我有一个Controller类。
此类需要不同的枚举值,具体取决于它的注入位置。我不想为控制器创建子类。
我该怎么做?
示例:
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 :(得分: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));
这就像一个魅力。