Reputation: 15799
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.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>
:
StoreAuthorizer
references? new StoreAuthorizer()
really is calling an impl of getInstance()
behind the scenes?Upvotes: 5
Views: 3802
Reputation: 110104
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.
Upvotes: 8