4

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.

tanyehzheng
  • 2,201
  • 1
  • 20
  • 33
  • I think I had the same question, but under another form. Instead of services I managed plugins. Basically, it involved Multibinder and private modules. I got it answered here: http://stackoverflow.com/questions/6625837/generalize-guices-robot-legs-example-with-multibinding – Olivier Grégoire Aug 29 '13 at 07:47
  • hi @tanyehzheng is it a web application or a desktop one? – Njax3SmmM2x2a0Zf7Hpd Dec 05 '13 at 11:07
  • Although I was trying on a desktop application, my question is not specific to whether it's a desktop application or a web application. – tanyehzheng Dec 05 '13 at 12:55

2 Answers2

2

ServiceManager.getServicesByState().get(RUNNING) returns the running services and ServiceManager.getServicesByState().values() returns all of the services managed by the ServiceManager.

gk5885
  • 3,742
  • 21
  • 16
0

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.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • If that's the intended way of using it, I think they should make it clear because it's easy to make mistake of forgetting to annotate as @Singleton and end up getting a new unstarted service instance. It's pretty hard to debug this kind of issue. – tanyehzheng Aug 30 '13 at 01:18
  • is it guice is also a service at the ServiceManager? – Njax3SmmM2x2a0Zf7Hpd Dec 04 '13 at 06:52