@GetMapping,模糊的映射

时间:2019-02-13 18:06:47

标签: java spring spring-boot

我正在尝试为@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创建一条路由?)

你能帮我吗?

感谢帮助。

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

@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);
    }
}

答案 1 :(得分:1)

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

@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));
}

文档link

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

指定多个值
@GetMapping(params = { "status", "date" })