Spring RestController模糊映射错误

时间:2015-08-06 05:07:35

标签: java spring spring-mvc spring-boot

我在Spring中设置了一个RestController,我有一个模糊的映射问题。我没有看到最后两个方法是如何模糊的,因为请求映射和方法名称是不同的。当我从上一个方法中删除方法规范时,问题就不存在了。

这是我的控制者:

@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.

2 个答案:

答案 0 :(得分:2)

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

您的方法addTag()removeTag()当前都映射到控制器的索引路径(/),因为它们在各方面都相似(方法,产生,参数)除了这个名字,春天哭得很厉害。

答案 1 :(得分:2)

使用RequestMapping属性尝试value

Value属性应该是唯一的,否则会引发异常。现在,在您的代码中,默认情况下,这两种方法都会重定向到/