How can I get all singleton instances from a Guice Injector?

ぃ、小莉子 提交于 2019-12-10 18:34:05

问题


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.


回答1:


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.

// Untested code. May need massaging.
private void closeAll(Injector injector) {
  for(Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) {
    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 overrode visitEagerSingleton and that you may have to modify the above to handle lazily-instantiated @Singleton instances with implicit bindings. Also note that if you bind(SomeInterface.class).to(SomeClosable.class).in(Singleton.class) you may need to make the SomeInterface.class Closable, 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.



来源:https://stackoverflow.com/questions/14033146/how-can-i-get-all-singleton-instances-from-a-guice-injector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!