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?Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.
Dependency Injection for Java Developers with Dagger & Guice Guice provides another way also to map bindings without creating a custom annoation. It allows so using @Named annotation.
Interface Module A module contributes configuration information, typically interface bindings, which will be used to create an Injector . A Guice-based application is ultimately composed of little more than a set of Module s and some bootstrapping code.
public abstract class AbstractModule extends java.lang.Object implements Module. A support class for Module s which reduces repetition and results in a more readable configuration. Simply extend this class, implement configure() , and call the inherited methods which mirror those found in Binder .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With