Is there an easy way to enumerate all the singleton instances already created by a Guice Injector? Or alternately a way to get all singletons that implement a specific interface?
I would like to find all singleton instances that implement java.io.Closeable so I can close them cleanly when my service is shut down.
This would be fairly easy to write using Guice’s SPI. Guice’s Injector instance exposes a getAllBindings() method that lets you iterate through all of the bindings.
Note that I only overrode
visitEagerSingletonand that you may have to modify the above to handle lazily-instantiated@Singletoninstances with implicit bindings. Also note that if youbind(SomeInterface.class).to(SomeClosable.class).in(Singleton.class)you may need to make theSomeInterface.classClosable, though you could also instantiate every Singleton (by putting the Closable check inside the scope visitor) to determine if the provided instance itself is Closable regardless of the key. You may also be able to use Reflection on the Binding’s Key to check whether the type is assignable to Closable.