2011-03-16 53 views
5

在實例我有這個類:獲得一個吉斯模塊

public class CompositeSecurityAuthorizer implements SecurityAuthorizer { 
    @inject @CompositeSecurityAuthorizerAnnot 
    List<SecurityAuthorizer> authorizers; //Field Injection 
} 

我想注入authorizers領域List<SecurityAuthorizer>值。

在我的模塊,我有以下幾點:

@Override 
protected void configure() { 
    bind(CompositeSecurityAuthorizer.class).in(Singleton.class); 
    bind(StoreAuthorizer.class).in(Singleton.class); 
    bind(SecurityAuthorizer.class) 
     .annotatedWith(CompositeSecurityAuthorizerAnnot.class) 
     .to(CompositeSecurityAuthorizer.class); 
} 

@Provides @CompositeSecurityAuthorizerAnnot 
List<SecurityAuthorizer> provideAuthorizersList() 
{ 
    List<SecurityAuthorizer> authList = new ArrayList<SecurityAuthorizer>(); 
    //How do I add StoreAuthorizer while maintaining a Singleton? 
    //Will the line below do it through Guice magic? 
    //authList.add(new StoreAuthorizer()); 
    return authList; 
} 

我的問題是嵌入代碼中的註釋。當我加入StoreAuthorizerList<SecurityAuthorizer>

  • 我如何確保它是相同的實例作爲其他StoreAuthorizer參考?
  • Guice只是在引擎蓋下做的事情,所以new StoreAuthorizer()真的在幕後調用了getInstance()的impl嗎?

回答

8

提供者方法允許注入參數。傳遞給此方法的StoreAuthorizer將是模塊中的單例綁定。如果你自己調用構造函數,Guice不會做任何不可思議的事情。

@Provides @CompositeSecurityAuthorizerAnnot 
List<SecurityAuthorizer> provideAuthorizersList(StoreAuthorizer storeAuthorizer) 
{ 
    List<SecurityAuthorizer> authList = new ArrayList<SecurityAuthorizer>(); 
    authList.add(storeAuthorizer); 
    return authList; 
} 

順便說一句,你可能要考慮使用吉斯Multibindings擴展來創建一個Set<SecurityAuthorizer>,而不是這樣做你自己。

+0

我忘記了MultiBinder。所以像這樣? Multibinder securityBinder = Multibinder.newSetBinder(binder(),SecurityAuthorizer.class); securityBinder.addBinding()。(StoreAuthorizer.class); – Snekse 2011-03-16 19:24:34

+0

@Snekse:是的,類似的東西。 – ColinD 2011-03-16 19:30:30

+0

Opps,看起來像Multibinder不兼容杜松子酒。 http://code.google.com/p/google-gin/issues/detail?id=111 – Snekse 2011-03-16 19:32:22