gpt4 book ai didi

java - 更好地实践 Spring MVC : Service with non-fixed dependency

转载 作者:行者123 更新时间:2023-12-01 12:13:32 26 4
gpt4 key购买 nike

我需要与基于 Spring 3.2 的新架构兼容。要求是:http 请求将到达 Controller ,该 Controller 具有定义需要哪种对象的属性。例如...mycontroller/load?objType='obj1'。

我的 Controller 将具有以下结构:

@Controller
public class myController{

private ObjectService objectService;

@Autowired
public setObjectService(ObjectService objectService){
this.objectService = objectService;
}

}

所以之后,我需要检查这个属性来决定我将使用哪个服务。例如,本例是 Obj1Service(方法:“load”)。所有这些服务都是从 ObjectService 扩展而来的,因此: 在每次传入调用中将 objectService 依赖项交换到 Obj1Service/Obj2Service 是一个好主意吗?例如:

if(objType.equals("obj1")) this.setObjectService(context.getBean("obj1Service"..))
if(objType.equals("obj2")) this.setObjectService(context.getBean("obj2Service"..))

我知道这不是一个很好的设计,但是我们需要将这个新模块与产生这种 http 请求的其他系统集成。继承是必要的,因为我们在很多服务的代码中都有非常相似的行为,但是在内部方法上进行了修改,所以部分行为将放在ObjectService中(它不是抽象的),而其他部分代码将放在其中 children 。还有其他更合适的方法来做到这一点吗?或者您认为这是一个可以接受的解决方案?

谢谢!

最佳答案

您可以对所有服务使用map,并在每个 Controller 方法中获取适当的服务。

假设您有两项服务:

@Service("obj1")
public class ObjectServiceImpl1 implements ObjectService {
...
}

@Service("obj2")
public class ObjectServiceImpl2 implements ObjectService {
...
}

在你的 Controller 中:

private Map<String, ObjectService> objectServices;

@Autowired
public setObjectServices(Map<String, ObjectService> objectServices){
this.objectServices= objectServices;
}

Spring 将使用按名称映射的所有 ObjectService bean 注入(inject)映射。

load?objType=obj1 处理程序中,您将得到如下内容:

objectServices.get("obj1").doSomething(); // will use ObjectServiceImpl1 

load?objType=obj2 处理程序相同:

objectServices.get("obj2").doSomething(); // will use ObjectServiceImpl2 

等等。

关于java - 更好地实践 Spring MVC : Service with non-fixed dependency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27134564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com