Guice Dynamic Binding,获取实例

时间:2016-09-16 09:28:16

标签: java dependency-injection guice

我是Dependency Injection& 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 个答案:

答案 0 :(得分: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());
    }
}