带注释的单例实例的 guice 注入器 getInstance

guice injector getInstance of annotated singleton instance

我正在使用带有 Guice 的 Restlet。

在我的 Guice 中定义了一个 CachedThreadPool:

@Provides
@Singleton
@Named("name0")
public ExecutorService provideAutoDisconnectThreadPool () {
    return Executors.newCachedThreadPool();
}

想在服务器停止时关闭线程池,所以在我的 restlet.Application 中,我使用注入器来获取实例:

@Override
public void stop() throws Exception {
    LOGGER.info("stopping...");
    // shutdown threadPool
    injector.getInstance(ExecutorService.class).shutdown();
    super.stop();
    LOGGER.info("stopped");
}

但是,程序出现以下错误:

com.google.inject.ConfigurationException: Guice configuration errors:

1) No implementation for java.util.concurrent.ExecutorService was bound.
 while locating java.util.concurrent.ExecutorService

1 error
at    com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1004)
at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1009)

那么,如何在应用程序停止时获取线程池实例。

Named 是一个 binding annotation,所以这种情况下的注入密钥是 ExecutorService.class and @Named("name0"):

injector.getInstance(Key.get(ExecutorService.class, Names.named("name0")))