我的文件中有一张地图,如:
workflowProperties1 = { "key1" : "value1"; "key2": "value2"; };
workflowProperties2 = { "key1" : "value1"; "key2": "value2"; };
Run Code Online (Sandbox Code Playgroud)
我想使用guice在类的构造函数中注入此映射.我做的事情如下:
@Inject public myClass(@Named("workflowProperties1") Map<String,String> someMap) { }
Run Code Online (Sandbox Code Playgroud)
有人可以建议我如何基于静态参数值在myClass中注入两个地图中的一个(workflowProperties1或workflowProperties2)?
解决方案可能是使用Guice Multibindings.请注意,多绑定器不包含在核心Guice中,因此您需要额外的依赖关系com.google.inject.extensions:guice-multibindings.
然后你可以定义你的绑定模块,就像这样(实际上你将从你的文件中提取键/值-s):
@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");
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以轻松地"根据静态参数值"注入正确的地图,例如:
private static final String STATIC_PARAMETER_VALUE = "workflowProperties1";
@Inject
@Named(STATIC_PARAMETER_VALUE)
Map<String,String> someMap;
Run Code Online (Sandbox Code Playgroud)