Spring Boot 中不明确的处理程序方法

Ambiguous handler methods in Spring Boot

我的 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));
}

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

但这给了我错误,说:

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

如何解决这个问题?

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

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