我有这堂课:
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;
}
我的问题已嵌入代码注释中。当我将StoreAuthorizer
添加到List<SecurityAuthorizer>
时:
StoreAuthorizer
引用的实例相同? new StoreAuthorizer()
真的在幕后调用了getInstance()
吗?答案 0 :(得分:8)
提供者方法允许注入参数。传递给此方法的StoreAuthorizer
将是模块中绑定的单例。如果你自己打电话给构造函数,Guice不会也不会做任何神奇的事情。
@Provides @CompositeSecurityAuthorizerAnnot
List<SecurityAuthorizer> provideAuthorizersList(StoreAuthorizer storeAuthorizer)
{
List<SecurityAuthorizer> authList = new ArrayList<SecurityAuthorizer>();
authList.add(storeAuthorizer);
return authList;
}
顺便说一句,您可能需要考虑使用Guice Multibindings扩展来创建Set<SecurityAuthorizer>
而不是自己这样做。