如何将路径变量映射到 spring-rest 中的实体

Teo*_*ali 5 java spring-restcontroller spring-rest

我在 Spring-RS 中得到了一些 REST 端点,它使用实体 id 作为路径变量。大多数时候,该方法所做的第一件事是使用 id 检索实体。有没有办法自动将 id 映射到实体,仅将实体作为方法参数?

现在的情况 :

@RequestMapping(path="/{entityId})
public void method(@PathVariable String entityId) {
    Entity entity = entityRepository.findOne(entityId);
    //Do some work
}
Run Code Online (Sandbox Code Playgroud)

我想要什么:

@RequestMapping(path="/{entityId})
public void method(@PathVariable Entity entityId) {
    //Do some work
}
Run Code Online (Sandbox Code Playgroud)

dda*_*lis -1

你可以这样做:

@RequestMapping(value = "/doctor/appointments/{start}/{end}", produces = "application/json")
@ResponseBody
public List<Appointment> showAppointments(Model model, @ModelAttribute("start") Date start,
        @ModelAttribute("end") Date end, Principal principal) {

}
Run Code Online (Sandbox Code Playgroud)

获取您的自定义对象,Spring 会尝试将参数转换为给定类型。

出于安全原因,我大多数时候更喜欢传递 id。