我想迭代Guice容器的所有绑定对象。例如,当我调用getInstance
时,我希望Guice容器已经创建了UserManagerImpl
的实例。但是Guice创造了新的。
GuiceModule mainModule = new GuiceModule();
Injector injector = Guice.createInjector(mainModule);
Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
for (Binding<?> binding : bindings.values()) {
Object instance = injector.getInstance(binding.getKey());
}
以下是GuiceModule的配置示例。
public class GuiceModule extends AbstractModule {
@Override
protected void configure() {
bind(UserManager.class).to(UserManagerImpl.class).in(Singleton.class);
}
}
答案 0 :(得分:4)
您应该使用此绑定:
bind(UserManagerImpl.class).in(Singleton.class);
bind(UserManager.class).to(UserManagerImpl.class);
这需要注意UserManagerImpl
是真正的单身人而不是界面。这样就可以调用两者
injector.getInstance(UserManager.class);
injector.getInstance(UserManagerImpl.class);
将导致相同的实例。通过遍历所有绑定并在其上调用getInstance
,您还调用了后者 - 未标记为Singleton
和宾果游戏 - 您有多个实例。
...所以
但是如果由于某些其他原因你仍然必须得到所有单身人士:使用BindingScopingVisitor
这样:
BindingScopingVisitor<Boolean> visitor = new IsSingletonBindingScopingVisitor();
Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
for (Binding<?> binding : bindings.values()) {
Key<?> key = binding.getKey();
System.out.println("Examing key "+ key);
Boolean foundSingleton = binding.acceptScopingVisitor(visitor);
if( foundSingleton ) {
Object instance = injector.getInstance(key);
System.out.println("\tsingleton: " + instance);
}
}
class IsSingletonBindingScopingVisitor implements BindingScopingVisitor<Boolean> {
@Override
public Boolean visitEagerSingleton() {
System.out.println("\tfound eager singleton");
return Boolean.TRUE;
}
@Override
public Boolean visitScope(Scope scope) {
System.out.println("\t scope: "+scope);
return scope == Scopes.SINGLETON;
}
@Override
public Boolean visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
System.out.println("\t scope annotation: "+scopeAnnotation);
return scopeAnnotation == Singleton.class;
}
@Override
public Boolean visitNoScoping() {
return Boolean.FALSE;
}
}
输出将是这样的:
Examing key Key[type=com.google.inject.Injector, annotation=[none]]
Examing key Key[type=java.util.logging.Logger, annotation=[none]]
Examing key Key[type=com.google.inject.Stage, annotation=[none]]
found eager singleton
singleton: DEVELOPMENT
Examing key Key[type=UserManager, annotation=[none]]
Examing key Key[type=UserManagerImpl, annotation=[none]]
scope: Scopes.SINGLETON
singleton: UserManagerImpl@1935d392