I have a map in my file like:
workflowProperties1 = { "key1" : "value1"; "key2": "value2"; };
workflowProperties2 = { "key1" : "value1"; "key2": "value2"; };
I want to inject this map in a constructor of a class using guice. I am doing something like:
@Inject public myClass(@Named("workflowProperties1") Map<String,String> someMap) { }
Can some one suggest how I inject one of the two maps (workflowProperties1 or workflowProperties2) in myClass above based on a static parameter value?
A solution might be to use Guice Multibindings. Please note that the multibinders are not included in the core Guice so you will need an extra dependency to com.google.inject.extensions:guice-multibindings
.
Then you may define your binding module, something like this (in reality you will extract the key/value-s from your file):
@Override
protected void configure()
{
MapBinder<String, String> wf1Binder = MapBinder.newMapBinder(
binder(),
String.class,
String.class, Names.named("workflowProperties1"));
wf1Binder.addBinding("WF1Key").toInstance("WF1Value");
MapBinder<String, String> wf2Binder = MapBinder.newMapBinder(
binder(),
String.class,
String.class, Names.named("workflowProperties2"));
wf2Binder.addBinding("WF2Key").toInstance("WF2Value");
}
Then you can easily inject the right map "based on a static parameter value" as you asked e.g:
private static final String STATIC_PARAMETER_VALUE = "workflowProperties1";
@Inject
@Named(STATIC_PARAMETER_VALUE)
Map<String,String> someMap;
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