2014-10-07 88 views
0

假設我有一個類,如下所示:吉斯:輔助注射和供應商

public class ComplicatedImpl implements Complicated { 
    @Inject 
    public ComplicatedImpl(Integer normal, @Assisted String assisted); 

    public void addListener(Listener listener); 
} 

現在,我有一個ComplicatedFactory像這樣:

public interface ComplicatedFactory { 
    public Complicated build(String assisted); 
} 

是否使用FactoryModuleBuilder時可能,綁定ComplicatedFactory這樣,當build()被調用時,我們做相當於

ComplicatedImpl impl = new ComplicatedImpl(normal, assisted); 
impl.addListener(listener); 
return impl; 

而不是正常情況下直接返回新的ComplicatedImpl

我整個的試圖綁定ComplicatedImpl某種形式的Provider,但似乎我在圈子與被繞來繞去......

回答

1

我不相信這是可能的吉斯; FactoryModuleBuilder除了將顯式構造函數參數與依賴關係混合以外,可以做的很少。幸運的是,寫一本手冊廠是相對容易:

public class ListeningComplicatedFactory { 
    @Inject Provider<Integer> normalProvider; 

    public Complicated createComplicated(String assisted, Listener listener) { 
    ComplicatedImpl impl = new ComplicatedImpl(normalProvider.get(), assisted); 

    // If ComplicatedImpl uses member injection, inject an Injector and call 
    // injector.injectMembers(impl) to call @Inject-annotated methods/fields. 

    impl.addListener(listener); 
    return impl; 
    } 
} 

如果你願意把addListenerComplicated界面上,你也有寫:注射ComplicatedFactory,創建新實例的包裝的選項,並調用addListener立即在他們身上。如果您綁定PrivateModule中的ComplicatedFactory,然後僅公開新的ComplicatedWrapperFactory,那麼這會特別有效,從而使您的ComplicatedWrapperFactory成爲創建新複雜實現的唯一方法。