簡體   English   中英

Guice 動態綁定,獲取實例

[英]Guice Dynamic Binding, get Instance

我是 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);
    }
}

至於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());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM