2013-03-09 2 views
1

Guice 컨테이너의 모든 바인딩 된 객체를 반복하고 싶습니다. 예를 들어, 내가 getInstance을 호출 할 때 Guice 컨테이너로 이미 UserManagerImpl이라는 인스턴스를 만들고 싶습니다. 그러나 Guice는 대신 새로운 것을 만듭니다.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

대신이 바인딩을 사용해야합니다

bind(UserManagerImpl.class).in(Singleton.class); 
    bind(UserManager.class).to(UserManagerImpl.class); 

이 돌봐 UserManagerImpl 진짜 싱글이 아닌 인터페이스입니다. 모두

injector.getInstance(UserManager.class); 
injector.getInstance(UserManagerImpl.class); 

를 호출 그 방법은 동일한 인스턴스가 발생합니다. 을 모두 반복하여 바인딩을 호출하고 getInstance을 호출하면 나중에 - Singleton으로 표시되지 않았고 몇 가지 인스턴스가 있습니다.

그래서 ....

그러나 당신은 여전히 ​​인해 다른 이유로 모든 싱글을 얻을해야하는 경우 :

:

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; 
    } 
} 

출력이 같은 것입니다 :이 같은 BindingScopingVisitor를 사용하여

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: [email protected]