在Guice获得所有受限制的单身人士

时间:2013-03-09 11:33:18

标签: java binding guice

我想迭代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);
     }
}

1 个答案:

答案 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