1

我想遍历 Guice 容器的所有绑定对象。例如,当我调用时,getInstance我想获取UserManagerImplGuice 容器已经创建的实例。但是 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);
     }
}
4

1 回答 1

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
于 2013-03-09T11:48:52.610 回答