我是新的依賴注入& 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);
}
}
我發現你的例子令人困惑。這看起來像靜態代碼。我會使用一個屬性文件(或類似的)爲用戶1到4創建命名綁定,然後使用您想註冊的屬性註釋RegisterService,並在構造函數 – pandaadb