我正在尝试为@GetMapping
创建一些路由。例如,localhost:8080/tasks
和localhost: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创建一条路由?)
你能帮助我吗 ?
感谢帮助。
最佳答案
来自另一个答案,因为这个更具体。
您可以通过指定所需的查询参数来缩小端点映射的范围。
@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" })