gpt4 book ai didi

java - 在 Spring 中使用 REST 调用来暴露服务层

转载 作者:行者123 更新时间:2023-11-30 05:54:33 24 4
gpt4 key购买 nike

我有一个现有的 Java 代码服务层,我想在某些 REST 调用中使用它。我想这样做的方法是让用户在 URL 中传递服务 ID,然后在后端查找服务和方法(在数据库或配置文件中)并调用它。例如:

http://foobar.com/rest/car

调用此 URL 时,我会获取“car”的 serviceId 并调用 CarService。我想我会有一个简单的配置:

car=com.foobar.services.CarService
house=com.foobar.services.HouseService
etc..

有没有办法使用 Spring 来做到这一点?我担心的一个问题不是调用服务,而是弄清楚调用哪个方法。如果我调用 http://foobar.com/services/car/red - 我如何传入“red”的方法参数并决定调用哪个方法?

这是一个在 Java 中的例子:

@RequestMapping(value = "{serviceId}")
@ResponseBody
public Object getMarshalledObject(@PathVariable String serviceId) {

if ("car".equals(serviceId)) {
return getCar();
}
throw new ServiceNotFoundException("Service ID not found.");
}

最佳答案

我会为每个服务制作单独的 Controller ,并让每个 Controller 在从请求中提取相关信息后委托(delegate)给其相应的服务。

由于 Controller 及其方法上 @RequestMapping 的性质,这应该非常简单:

@RequestMapping("/car")
class CarController {
@Autowired
private CarService service;

@RequestMapping("/{color}")
public Object getCarsByColor(@PathVariable String carColor) {
return service.getCarsByColor(houseColor);
}
}

@RequestMapping("/house")
class HouseController {
@Autowired
private HouseService service;

@RequestMapping("/{houseId}")
public Object getHouseById(@PathVariable int houseId) {
return service.getHouseById(houseId);
}
}

我们这里有两个不同的 Controller ,具有不同的服务,它们由应用于类的 @RequestMapping 映射。此外, Controller 方法由 url 中的其余路径元素调用。

关于java - 在 Spring 中使用 REST 调用来暴露服务层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9213451/

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