Getting an instance within a Guice Module
I have this class:
public class CompositeSecurityAuthorizer implements SecurityAuthorizer {
@inject @CompositeSecurityAuthorizerAnnot
List<SecurityAuthorizer> authorizers; //Field Injection
}
I want to inject the authorizers
field a List<SecurityAuthorizer>
value.
In my module , I have the following:
@Override
protected void configure() {
bind(CompositeSecurityAuthorizer.class).in(Singleton.class);
bind(StoreAuthorizer开发者_如何学JAVA.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;
}
My question is embedded in the code comments. When I'm adding StoreAuthorizer
to that List<SecurityAuthorizer>
:
- How do I ensure it's the same instance as other
StoreAuthorizer
references? - Is that something Guice is just doing under the hood, so
new StoreAuthorizer()
really is calling an impl ofgetInstance()
behind the scenes?
Provider methods allow injected arguments. The StoreAuthorizer
passed to the method here will be the singleton bound in your module. Guice doesn't and can't do anything magical if you call a constructor yourself.
@Provides @CompositeSecurityAuthorizerAnnot
List<SecurityAuthorizer> provideAuthorizersList(StoreAuthorizer storeAuthorizer)
{
List<SecurityAuthorizer> authList = new ArrayList<SecurityAuthorizer>();
authList.add(storeAuthorizer);
return authList;
}
As an aside, you may want to consider using the Guice Multibindings extension to create a Set<SecurityAuthorizer>
rather than doing this yourself.
精彩评论