有没有一种简单的方法来枚举 Guice 注入器已经创建的所有单例实例?或者另一种获取实现特定接口的所有单例的方法?
我想找到所有实现 java.io.Closeable 的单例实例,以便在服务关闭时可以干净地关闭它们。
使用 Guice 的 SPI 编写起来相当容易。 Guice 的 Injector 实例公开了一个获取所有绑定() https://google.github.io/guice/api-docs/latest/javadoc/com/google/inject/Injector.html#getAllBindings--允许您迭代所有绑定的方法。
// 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
可关闭,尽管您也可以实例化每个单例(通过将可关闭检查放在范围访问者内)来确定提供的实例本身是否可关闭,而不管键如何。您还可以在 Binding 的 Key 上使用 Reflection 来检查该类型是否可分配给 Closable。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)