具有不同 PathVariable 的相同休息端点

Gui*_*reg 3 java rest spring kotlin spring-boot

我正在尝试创建两个具有相同 uri 但类型不同的休息端点。第一个将按 EAN (Int) 搜索,第二个将按 id (String) 搜索。我可以以某种方式使端点过载吗?我在 Kotlin 中使用 Spring Boot

@GetMapping("/book/{ean}")
fun getABookByEan(@PathVariable ean: Int) : ResponseEntity<*> {
    repository.getByEan(ean)?.let {
        return ResponseEntity.status(HttpStatus.OK).body(it)
    }
    throw ItemNotFoundException()
}

@GetMapping("/book/{id}")
fun getABookById(@PathVariable id: String) : ResponseEntity<*> {
    repository.getById(id)?.let {
        return ResponseEntity.status(HttpStatus.OK).body(it)
    }
    throw ItemNotFoundException()
}
Run Code Online (Sandbox Code Playgroud)

在此之后,我得到了一个例外,即多个方法被映射到同一个端点。

...NestedServletException:请求处理失败;嵌套异常是 java.lang.IllegalStateException: Ambiguous handler methods mapping for HTTP path...

Gui*_*reg 6

我发现如果我想坚持使用我的 API,唯一的方法就是使用正则表达式。

@GetMapping("/book/{ean:[\\d]+}")

@GetMapping("/book/{id:^[0-9a-fA-F]{24}$}")
Run Code Online (Sandbox Code Playgroud)

有了它,MongoDB 生成的十六进制 24 字符可以与简单数字区分开来。如果有人找到更好的方法,请在评论中告诉我。