gpt4 book ai didi

java - Spring RestController 不明确的映射错误

转载 作者:行者123 更新时间:2023-12-01 16:56:39 28 4
gpt4 key购买 nike

我正在 Spring 中设置 RestController,但有一个不明确的映射问题。我不明白最后两个方法有什么歧义,因为请求映射和方法名称不同。当我从最后一个方法中删除方法规范时,问题就不再存在了。

这是我的 Controller :

@RestController
public class TagController {

@Autowired
private TagService tagService;

@RequestMapping(name = "/tag/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TagList> getTagList() {
TagList result = new TagList(tagService.list());
return new ResponseEntity<TagList>(result, HttpStatus.OK);
}

@RequestMapping(name = "/tag/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addTag(@RequestBody AlterTagForm form) {
try {
tagService.addTag(form.getArticleId(), form.getTagName());
return new ResponseEntity<>(HttpStatus.ACCEPTED);
} catch (EntityNotFoundException ex) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

@RequestMapping(name = "/tag/remove", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> removeTag(@RequestBody AlterTagForm form) {
try {
tagService.removeTag(form.getArticleId(), form.getTagName());
return new ResponseEntity<>(HttpStatus.ACCEPTED);
} catch (EntityNotFoundException ex) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}

这会导致此错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'tagController' bean method 
public org.springframework.http.ResponseEntity<?> com.example.article.controller.TagController.removeTag(com.example.admin.form.AlterTagForm)
to {[],methods=[POST],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}: There is already 'tagController' bean method
public org.springframework.http.ResponseEntity<?> com.example.article.controller.TagController.addTag(com.example.admin.form.AlterTagForm) mapped.

最佳答案

在您的@RequestMapping注释中,您应该使用value属性设置路径。 value 属性确定您的方法应处理的路径,而 name 属性仅用于标识 Spring 环境中的映射。

您的方法 addTag()removeTag() 目前都映射到 Controller 的索引路径 (/),并且从那时起它们在各方面都很相似(方法、生成、参数),除了名称之外,Spring 喊犯规了。

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

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