Java – how do I get all singleton instances from Guice injector?

Is there a simple way to enumerate all singleton instances that Guice injector has created? Or another way to get all the singletons that implement a particular interface?

I want to find all the implementations of Java io. A singleton instance of closeable so that when my services are shut down, I can shut them down cleanly

Solution

It's quite easy to write using Guice's SPI Guice's injector instance exposes a getallbindings () method that allows you to traverse all bindings

// Untested code. May need massaging.
private void closeAll(Injector injector) {
  for(Map.Entry<Key<?>,Binding<?>> entry : injector.getAllBindings()) {
    final Binding<?> binding = entry.getValue();
    if (Closeable.class.isAssignablefrom(
        entry.getKey().getTypeLiteral().getRawType())) {
      binding.accept(new DefaultBindingscopingVisitor<Void>() {
        @Override public Void visitEagerSingleton() {
          Closeable instance = (Closeable) (binding.getProvider().get());
          try {
            instance.close();
          } catch (IOException e) {
            // log this?
          }
          return null;
        }
      });
    }
  }
}

Note that I only override visiteagersingleton, and you may have to modify the above to use implicit binding to handle deferred instantiated @ singleton instances Also note that if you bind (someinterface. Class) to(SomeClosable.class). In (singleton. Class), you may need to make someinterface Class closed, although you can also instantiate each singleton (by putting the closed check into it) to determine whether the provided instance itself is closed, regardless of the key You can also use reflection on the binding key to check whether the type can be assigned to closed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>