2016-09-16 77 views
1

我是新的依賴注入& Guice in Java。我有一個動態注入合適對象的問題。Guice動態綁定,獲取實例

例如:

public class Main { 
    public static void main(String[] args) { 
     Injector injector = Guice.createInjector(new MyModule()); 

     StudentStore studentStore = injector.getInstance(StudentStore.class); 
     RegisterService registerService = injector.getInstance(RegisterService.class); 

     registerService.register("First User"); 
     registerService.register("Second User"); 

     //Now I would like to use OfflineRegisterService.class - is it good idea to do it here? 
     registerService = injector.getInstance(OfflineRegisterService.class); 

     registerService.register("Third User"); 
     registerService.register("Fourth User"); 

     System.out.println(studentStore.size()); 
    } 
} 

它的工作原理,但它是做最好的主意?

public class MyModule extends AbstractModule { 
    @Override 
    protected void configure() { 
     bind(StudentStore.class).to(MemoryStudentStore.class); 
     bind(RegisterService.class).to(OnlineRegisterService.class); 
    } 
} 
+0

我發現你的例子令人困惑。這看起來像靜態代碼。我會使用一個屬性文件(或類似的)爲用戶1到4創建命名綁定,然後使用您想註冊的屬性註釋RegisterService,並在構造函數 – pandaadb

回答

1

至於Guice,你的解決方案是好的。爲了代碼可讀性,我會爲離線代碼創建一個新的局部變量。所以你總是知道你正在使用哪一個:

public class Main { 
    public static void main(String[] args) { 
     Injector injector = Guice.createInjector(new MyModule()); 

     final StudentStore studentStore = injector.getInstance(StudentStore.class); // final prevents reassignment 
     // do some stuff 

     //Now I would like to use OfflineRegisterService.class - is it good idea to do it here? 
     final offlineRegisterService = injector.getInstance(OfflineRegisterService.class); // final too 

     offlineRegisterService.register("Third User"); 
     offlineRegisterService.register("Fourth User"); 

     System.out.println(studentStore.size()); 
    } 
} 
+0

中執行。謝謝你的回答。你說「很好」。它會更好嗎? –

+0

對於這個靜態代碼,這是完美的。一些真實的場景會很有用。例如。你需要不同的寄存器來測試產品嗎?你想基於配置在寄存器之間切換嗎? –

+0

我想根據用戶決定在註冊之間切換。如果他想在線註冊(他將在網上註冊),如果他想在線下注冊(他可以打印表格)。我應該創建下一個接口和類來管理這種情況嗎? –

相關問題