假设我的HigherLevelBean
取决于LittleService
。 LittleService
是一个包含两个实现的接口。
没有静态或半静态的方法来判断应该使用哪两个实现,它们都是动态的(事实上是会话范围的)。当此用户请求使用LegacyLittleService
时,对于其他用户的请求,请使用NewShinyLittleService
。
服务不会那么小。它们将具有需要注入的自己的依赖项,它们可能来自两个不同的应用程序上下文。考虑在两个不同的模式/数据模型上使用一个应用程序。
如何实现这种运行时动态?理想情况下使用注释驱动配置。我的选择是什么,它们的优点和缺点是什么?
答案 0 :(得分:1)
你可以简单地建立一个工厂,注入两个服务:
@Component
public class LittleServiceFactory {
@Autowired
private LegacyLittleService legacy;
@Autowired
private NewShinyLittleService newShiny;
@Autowired
private TheSessionScopedBean theSessionScopedBean;
public LittleService get() {
if (theSessionScopedBean.shouldUseLegacy()) {
return legacy;
}
else {
return newShiny;
}
}
}
现在将此工厂注入您想要的任何地方,并调用get()来访问相应的LittleService实例。