Guice 中 Key 中的 get() 方法

get() method in Key in Guice

现在我对 Key class 中的 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。虽然这只是我的假设,但是这段代码使用了Keyclass中的哪个方法?

Key.get 的所有重载都以 type 作为第一个参数和 annotation class 或 instance作为可选的第二个参数。 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))

因为您的调用具有第二个参数,即 class,它们必须是上面的第三个重载(标记为 "THIS ONE"),需要两个 classes:其中一个类型,以及注解之一 class.

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

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

第一个和第二个参数之间没有关系,第二个参数可以是任何注解。 您应该通过不同的注解(在本例中为 DatabaseService 和 WebserverService)将 Service class 绑定到不同的实现。