当前位置: 代码迷 >> java >> @GetMapping,模糊的映射
  详细解决方案

@GetMapping,模糊的映射

热度:121   发布时间:2023-07-31 11:43:28.0

我正在尝试为@GetMapping创建一些路由。 例如, localhost:8080/taskslocalhost:8080/tasks/?status=...

因此,我创建了以下几种方法。

调节器

@RestController
@RequestMapping(value = "/tasks", produces = MediaType.APPLICATION_JSON_VALUE)
@ExposesResourceFor(Task.class)
public class TaskRepresentation {

    private final TaskResource taskResource;

    public TaskRepresentation(TaskResource taskResource) {
        this.taskResource = taskResource;
    }

    @GetMapping
    public ResponseEntity<?> getAllTasks() {
        return new ResponseEntity<>(this.taskResource.findAll(), HttpStatus.OK);
    }

    @GetMapping
    public ResponseEntity<?> getTasksStatus(@RequestParam("status") int status) {
        return new ResponseEntity<>(this.taskResource.getTasksByStatus(status), HttpStatus.OK);
    }
}

资源

@RepositoryRestResource(collectionResourceRel = "task")
public interface TaskResource extends JpaRepository<Task, String> {

    @GetMapping
    List<Tache> getTasksByStatus(@RequestParam int status);

}

错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'taskRepresentation' method 
public org.springframework.http.ResponseEntity<?> org.miage.tache.boundary.TacheRepresentation.getTasksStatus(int)
to {GET /tasks, produces [application/json]}: There is already 'taskRepresentation' bean method

(唯一的解决方案是仅使用可选参数为@GetMapping创建一条路由?)

你能帮助我吗 ?

感谢帮助。

您可以执行以下操作:

@RestController
@RequestMapping(value = "/tasks", produces = MediaType.APPLICATION_JSON_VALUE)
@ExposesResourceFor(Task.class)
public class TaskRepresentation {

    private final TaskResource taskResource;

    public TaskRepresentation(TaskResource taskResource) {
        this.taskResource = taskResource;
    }

    @GetMapping
    public ResponseEntity<?> getTasksStatus(@RequestParam(value="status", required=false) Integer status) {
        if(status==null){
            return new ResponseEntity<>(this.taskResource.findAll(), HttpStatus.OK);
        }
        return new ResponseEntity<>(this.taskResource.getTasksByStatus(status.intValue()), HttpStatus.OK);
    }
}

来自另一个答案,因为这个更具体。 您可以通过指定所需的查询参数来缩小端点映射的范围。

@GetMapping
public ResponseEntity<?> getAllTasks() {
   return ResponseEntity.ok().body(this.taskResource.findAll());
}

@GetMapping(params = "status")
public ResponseEntity<?> getAllTasksWithStatus(@RequestParam("status") final int status) {
   return ResponseEntity.ok().body(this.tacheResource.getTachesByEtat(status));
}

文档 。

注意:由于params是一个数组,因此可以使用

@GetMapping(params = { "status", "date" })