简体   繁体   English

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

[英]guice injector getInstance of annotated singleton instance

I'm using Restlet with Guice. 我正在使用Restlet和Guice。

A CachedThreadPool is definded in my Guice: CachedThreadPool在我的Guice中被定义:

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

Wanted to shutdown the threadPool when the server is stops, so in my restlet.Application, I use injector to get the instance: 想在服务器停止时关闭threadPool,所以在我的restlet.Application中,我使用inject来获取实例:

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

However, the program got the error with: 但是,该程序得到错误:

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)

So, how can I get the threadPool instance when application stops. 那么,如何在应用程序停止时获取threadPool实例。

Named绑定注释 ,因此在这种情况下注入键是ExecutorService.class @Named("name0")

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM