您应该改用此绑定:
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