Search code examples
javadependency-injectionguice

get() method in Key in Guice


Now I am confused with get methods in Key class. My question is just about which a get method is used in the below code. But, I can't find the appropriate method. Of course,I have already checked the API reference, but I couldn't find the likely method.
See this code.

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

The second argument seems to be T extends V where the first argument is V. Although this is just my assumption, so which method in Key class is used in this code?


Solution

  • All overloads of Key.get feature a type as the first argument and an annotation class or instance as the optional second argument. 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))
    

    Because your calls feature a second argument that is a class, they must be the third overload above (marked "THIS ONE") that take two classes: One of the type, and one of the annotation class.

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