java - Guice 中 Key 中的 get() 方法

标签 java dependency-injection guice

现在我对 Key 类中的 get 方法感到困惑。 我的问题是下面的代码中使用了哪个 get 方法。 但是,我找不到合适的方法。当然,我已经检查了API引用,但我找不到可能的方法。
请参阅此代码。

public static void main(String[] args) throws Exception {
    Injector injector = Guice.createInjector(
        new DatabaseModule(),
        new WebserverModule(),
        ...
    );

    Service databaseConnectionPool = injector.getInstance(
        Key.get(Service.class, DatabaseService.class));
    databaseConnectionPool.start();
    addShutdownHook(databaseConnectionPool);

    Service webserver = injector.getInstance(
        Key.get(Service.class, WebserverService.class));
    webserver.start();
    addShutdownHook(webserver);
  }

第二个参数似乎是T extends V,其中第一个参数是V。虽然这只是我的假设,那么这段代码中使用了 Key 类中的哪个方法呢?

最佳答案

Key.get 的所有重载都将类型作为第一个参数,将注释类或实例作为可选的第二个参数。 See the docs.

Key.get(Class<T> type)
Key.get(Class<T> type, Annotation annotation)
Key.get(Class<T> type, Class<? extends Annotation> annotationType)  // THIS ONE
Key.get(Type type)
Key.get(Type type, Annotation annotation))
Key.get(Type type, Class<? extends Annotation> annotationType))
Key.get(TypeLiteral<T> typeLiteral)
Key.get(TypeLiteral<T> typeLiteral, Annotation annotation))
Key.get(TypeLiteral<T> typeLiteral, Class<? extends Annotation> annotationType))

因为您的调用具有第二个参数(即类),所以它们必须是上面的第三个重载(标记为“THIS ONE”),该重载采用两个类:一个是类型,另一个是注释类。

// Matches injections of "@DatabaseService Service"
Key.get(Service.class, DatabaseService.class)

// Matches injections of "@WebserverService Service"
Key.get(Service.class, WebserverService.class)

关于java - Guice 中 Key 中的 get() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42216507/

相关文章:

gwt - 使用 AOP、Guice 和新的 RequestFactories 进行身份验证

java - Guice - 从覆盖内访问原始值

Java Runtime.exec() -- 是否可以将流输出与 wait()/notify() 同步?

c# - ASP.NET MVC 按请求注入(inject)

java - ComponentScan excludeFilters 在 Spring 4.0.6.RELEASE 中不起作用

java - Play Framework 2.4 docker镜像运行错误

java - 配置 Spring Data Repository 类以针对读取/选择方法命中 read_replica_db 并针对写入/插入方法命中 main_db ?

java - 我不知道如何将树插入堆栈

java - Selvin 在 android 中集成 linkedin 的代码

ios - 使用 Swinject 将 Model 类实例注入(inject) Swift 中的 View 类实例