我有一个组件-子组件关系。每个人都有不同的作用域,并使用他们自己的模块,这提供了相同类型的谦逊。我需要的是基于范围的不同的对象实例化。匕首不允许这样做,因为我会有“多个绑定”。如果没有@Named限定符,我将如何解决这个问题?例如,是否有一种在子组件中覆盖的方法?
//Higher scoped object (in component)
@Provides
@ClientScope
ISupResRankStrategy iSupResRankStrategy(@Named("GlobalModelConfig") JsonNode configSubTree,
Lazy<SortByMagnitudeSum> strat1,
Lazy<SortByShadowPercentage> strat2) {
@SuppressWarnings("rawtypes")
Map<String, Lazy> availableStrategies = new HashMap<>();
availableStrategies.put(SortByMagnitudeSum.class.getSimpleName(), strat1);
availableStrategies.put(SortByShadowPercentage.class.getSimpleName(), strat2);
String configuredStrategy = configSubTree.findValue("ISupResRankStrategy").asText();
return (ISupResRankStrategy) availableStrategies.get(configuredStrategy).get();
}//lower scoped object (in subcomponent)
@Provides
@ModelScope
ISupResRankStrategy iSupResRankStrategy(@Named("TradeModelConfig") JsonNode configSubTree,
Lazy<SortByMagnitudeSum> strat1,
Lazy<SortByShadowPercentage> strat2) {
@SuppressWarnings("rawtypes")
Map<String, Lazy> availableStrategies = new HashMap<>();
availableStrategies.put(SortByMagnitudeSum.class.getSimpleName(), strat1);
availableStrategies.put(SortByShadowPercentage.class.getSimpleName(), strat2);
String configuredStrategy = configSubTree.findValue("ISupResRankStrategy").asText();
return (ISupResRankStrategy) availableStrategies.get(configuredStrategy).get();
}发布于 2019-04-06 09:58:45
匕首不允许这样做,因为我会有“多个绑定”。如果没有@Named限定符,我将如何解决这个问题?例如,是否有一种在子组件中覆盖的方法?
没有。您不能同时拥有两个具有不同作用域的相同类型的对象。达格怎么知道你想要哪一个?
拥有相同类型的多个对象
@Qualifier,@Named是其中之一,但是您可以用更好的名称创建自己的名称,例如@Client、@Model发布于 2019-04-08 11:16:38
使用“限定符,”命名。您可以重载DI
为例
@Provides @Named("type1")
Model provideModel() {
return new Model();
}
@Provides @Named("type2")
Model provideModeWithContext(Context context) {
return new Model(context);
}https://stackoverflow.com/questions/55539768
复制相似问题