gpt4 book ai didi

java - @GetMapping,不明确的映射

转载 作者:行者123 更新时间:2023-12-01 17:46:23 27 4
gpt4 key购买 nike

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

所以我创建了如下几个方法。

Controller

@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.taskResource.getTasksByStatus(status));
}

文档 link .

注意:由于 params 是一个数组,因此您可以使用 指定多个值

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

关于java - @GetMapping,不明确的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54676727/

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