Tav*_*nes 10 java guice guice-3
如果某些Guice范围使用不正确,我有一些测试我想失败.例如,a @Singleton不应该有任何@RequestScoped或@TestScoped依赖(Provider<>当然,s是可以的).
在生产中,这部分地得到了解决,因为在输入范围之前将构建热切的单体,从而产生OutOfScopeExceptions.但在开发过程中,单例将在范围内懒洋洋地创建,并且没有明显的问题.
从这 两个未解决的问题来看,似乎没有简单的内置方法来做到这一点.我可以使用SPI实现这一目标吗?我尝试使用a TypeListener但不清楚如何获取给定类型的依赖项.
以下是我如何通过 Guice 4.0 beta 版使用ProvisionListener. 我尝试过TypeListener,但似乎TypeListeners 在 Guice 必然具有该类型依赖项的绑定之前被调用。这导致了异常,甚至在一种情况下导致了死锁。
private static class ScopeValidator implements ProvisionListener {
private @Inject Injector injector;
private @Inject WhateverScope scope;
@Override
public <T> void onProvision(ProvisionInvocation<T> provision) {
if (injector == null) {
// The injector isn't created yet, just return. This isn't a
// problem because any scope violations will be caught by
// WhateverScope itself here (throwing an OutOfScopeException)
return;
}
Binding<?> binding = provision.getBinding();
Key<?> key = binding.getKey();
if (Scopes.isSingleton(binding) && binding instanceof HasDependencies) {
Set<Dependency<?>> dependencies = ((HasDependencies) binding).getDependencies();
for (Dependency<?> dependency : dependencies) {
Key<?> dependencyKey = dependency.getKey();
Binding<?> dependencyBinding = injector.getExistingBinding(dependencyKey);
if (dependencyBinding != null && Scopes.isScoped(dependencyBinding, whateverScope, WhateverScoped.class)) {
throw new ProvisionException(String.format(
"Singleton %s depends on @WhateverScoped %s",
key, dependencyKey));
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)