2013-11-01 4 views
1

컨트롤러 클래스가 있습니다.GUICE : 범위에 따라 값이 달라집니다.

이 클래스는 주입되는 위치에 따라 다른 enum 값이 필요합니다. 컨트롤러의 하위 클래스를 만들고 싶지 않습니다.

어떻게하면됩니까?

예 :

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; 
} 

이 우아한 수행 할 수 있습니까? 모듈을 어떻게 구성합니까?

모듈이 현재처럼 보이는 : 나는 PrivateBinder 내 문제를 해결 한

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

:이 마법처럼 작동

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

관련 문제