我有这个类:
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
引用相同的实例? - 这是Guice在幕后自动完成的吗,因此
new StoreAuthorizer()
实际上是在幕后调用getInstance()
的实现?
Multibinder securityBinder = Multibinder.newSetBinder(binder(), SecurityAuthorizer.class);
securityBinder.addBinding().to(StoreAuthorizer.class);
- SnekseSecurityAuthorizer
对象添加到该authList
中,您的回答会有所不同吗? - SnekseSecurityAuthorizer
参数传递给该方法,并且可以通过绑定注释、类型或其他方式进行区分。这样做很丑陋,但我认为应该可以运行。 - ColinD