如何在Guice注入中使用Guava ServiceManager [英] How to use Guava ServiceManager with Guice Injection
本文介绍了如何在Guice注入中使用Guava ServiceManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如此处所述,可以通过
ServiceManager manager = injector.getInstance(ServiceManager.class);
为完成这项工作,我在Guice模块中添加了以下内容:
To make this work, I added the following in my Guice module:
@Provides
public Set<Service> services(){
return ImmutableSet.<Service>of(MyService());
}
在我的主班上,
ServiceManager manager = injector.getInstance(ServiceManager.class);
manager.startAsync().awaitHealthy();
如何获取已启动服务的实例?
How do I get instances of the started services?
p.s.将服务设置为@Singleton感觉很容易.
p.s. Setting the services to be @Singleton feels like a hack.
推荐答案
在我看来,将服务设置为@Singleton
根本不是黑客.那可能就是我要做的.
In my opinion, setting the services to be @Singleton
isn't a hack at all. That's probably what I'd do.
@Provides @Singleton
public MyService myService() {
return new MyService();
}
@Provides
public Set<Service> services(MyService myService) {
return ImmutableSet.<Service>of(myService);
}
然后,您可以将所需的任何特定服务实例注入所需的任何位置.
Then you can just inject any particular service instance you want anywhere you want.
这篇关于如何在Guice注入中使用Guava ServiceManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文