2014-12-16 3 views
0

이상한 점이 있습니다. 키가 더있는 경우 (이 가능성이 필요하고 특정 상황에서 유용 매우 복잡하지만 보인다Guice : 모듈 삽입 및 설치

public class DependentModule extends AbstractModule { 
    private final String key; 

    @Inject public DependentModule(@Named("key") String key) { this.key = key; } 

    @Override 
    public void configure() { 
     // Configure bindings that make use of key... 
    } 
} 

Injector parent = Guice.createInjector(new ParentModule()); 
Injector child = parent.createChildInjector(parent.getInstance(DependentModule.class)); 
// Now just ignore parent and work with child exclusively 

:

public class ParentModule extends AbstractModule { 
    @Override 
    public void configure() { 
     bindConstant().annotatedWith(Names.named("key")).to("key"); 
    } 
} 

그런 다음 우리는이 같은이 :이 같은 모듈이 있다고 가정 복잡한 데이터 유형). 그럼에도 불구하고 ParentModule이 키를 바인딩하고 키를 사용하여 DependentModule을 만들고 생성 된 DependentModule을 설치하도록이 코드를 재구성하는 방법이 있습니까? 즉, 소비자가이 두 개의 인젝터 트릭을 수행하는 대신 단일 인젝터를 간단하게 사용할 수 있도록하는 것입니다.

+1

당신이 무엇을 요구하고 있는지 분명하지 않습니다. 코드가 수행해야하는 작업을 설명하는 SSCCE를 작성하십시오. – The111

답변

3

무언가를 주입 한 다음 설치할 수 없습니다. 주입은 모든 configure() 방법이 실행 된 후에 만 ​​발생합니다. 너무 늦었습니다. 그러나 당신은 이것을 할 수 있습니다 :

public class MyModule extends AbstractModule { 
    @Override 
    public void configure() { 
     bindConstant().annotatedWith(Names.named("key")).to("key"); 
    } 

    @Provides 
    Dependency provideDependency(@Named("key") String key) { 
     // Use key here 
    } 
}