【问题标题】:Ambiguous handler methods in Spring BootSpring Boot 中不明确的处理程序方法
【发布时间】:2020-01-05 03:22:13
【问题描述】:

我的 Spring Boot 应用程序中有这两个 GetMapping 方法:

@GetMapping("/user/{id}")
User one(@PathVariable Long id) {
    return repository.findById(id)
            .orElseThrow(() -> new UserNotFoundException(id));
}



@GetMapping("/user/{uid}")
User one(@PathVariable String uid) {
    return repository.findByDisplayName(uid);
            //.orElseThrow(() -> new UserNotFoundException(id));
}

我想通过userID(自动生成)或uniqueUserID(用户创建的String,如果可用)来GetMapping

但这给了我错误,说:

java.lang.IllegalStateException:为“/user/dis1”映射的不明确的处理程序方法:{com.mua.cse616.Model.User com.mua.cse616.Controller.UserController.one(java.lang.长),com.mua.cse616.Model.User com.mua.cse616.Controller.UserController.one(java.lang.String)}

如何解决?

【问题讨论】:

  • 映射一模一样,启动时解析表达式不知道类型。您可以尝试通过在 id 部分之后使用额外的正则表达式来限制第一个(数字)。尝试@GetMapping("/user/{id:\\d+}"),但是这假定uid 始终包含非数字字符,否则匹配将不起作用。

标签: spring spring-boot jpa h2 path-variables


【解决方案1】:

您必须为其中一个映射设置另一个名称。
当您的控制器收到/user/1234 时,它无法猜测1234 是否必须被解析为字符串或Long,因此它无法选择必须调用哪个方法。
这就是为什么相同的模式不能用于不同的 GET 方法的原因。如果您有 PostMappingGetMapping,则可以重用该模式,但就您而言,这不是最干净的解决方案。

@GetMapping("/user/{id}")
User one(@PathVariable Long id) {
    return repository.findById(id)
            .orElseThrow(() -> new UserNotFoundException(id));
}


// Mapping changed to handle calls like /user/uid/2345-ABCD-5678
@GetMapping("/user/uid/{uid}")
User one(@PathVariable String uid) {
    return repository.findByDisplayName(uid);
            //.orElseThrow(() -> new UserNotFoundException(id));
}

【讨论】:

  • 我不这样做,而是接受String,然后解析、验证,这就是我正在尝试做的工作。顺便说一句,非常感谢您的帮助。
猜你喜欢
  • 2017-11-16
  • 2021-01-12
  • 2022-01-05
  • 2018-11-07
  • 2013-12-08
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 2019-06-20
相关资源
最近更新 更多