问题
As mentioned here, Guava ServiceManager can be obtained by
ServiceManager manager = injector.getInstance(ServiceManager.class);
To make this work, I added the following in my Guice module:
@Provides
public Set<Service> services(){
return ImmutableSet.<Service>of(MyService());
}
In my main class,
ServiceManager manager = injector.getInstance(ServiceManager.class);
manager.startAsync().awaitHealthy();
How do I get instances of the started services?
p.s. Setting the services to be @Singleton feels like a hack.
回答1:
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.
回答2:
ServiceManager.getServicesByState().get(RUNNING)
returns the running services and ServiceManager.getServicesByState().values()
returns all of the services managed by the ServiceManager.
来源:https://stackoverflow.com/questions/18502650/how-to-use-guava-servicemanager-with-guice-injection