如何从Guice注射器获得所有单例实例? [英] How can I get all singleton instances from a Guice Injector?

查看:107
本文介绍了如何从Guice注射器获得所有单例实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以枚举Guice Injector已经创建的所有单例实例?或者是获取所有实现特定接口的单例的一种方法?

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?

我想找到所有实现java.io.Closeable的单例实例,以便我可以干净地关闭它们当我的服务关闭时。

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.

推荐答案

使用Guice的SPI编写起来相当容易。 Guice的Injector实例公开了 getAllBindings()方法,可让您遍历所有绑定。

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;
        }
      });
    }
  }
}

请注意,我仅覆盖了 visitEagerSingleton ,您可能需要修改上面的内容,以使用隐式绑定处理懒惰实例化的 @Singleton 实例。另请注意,如果您 bind(SomeInterface.class).to(SomeClosable.class).in(Singleton.class),则可能需要使 SomeInterface.class Closable,尽管您也可以实例化每个Singleton(通过将Closable检查放入作用域访问者中)来确定所提供的实例本身是否为Closable(与键无关)。您也许还可以使用绑定键上的Reflection来检查类型是否可分配给Closable。

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.

这篇关于如何从Guice注射器获得所有单例实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆