【发布时间】:2015-12-08 14:37:53
【问题描述】:
我有正常工作的 Spring Controller,其中我有一个按以下方式映射的方法
@RequestMapping(
value = "/users"
consumes = MimeTypeUtils.APPLICATION_JSON_VALUE,
produces = MimeTypeUtils.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public UserResponse retrieveUsers() {
return new UserResponse();
}
@RequestMapping(
value = "/contracts"
consumes = MimeTypeUtils.APPLICATION_JSON_VALUE,
produces = MimeTypeUtils.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ContractResponse retrieveContracts() {
return new ContractResponse();
}
这很好用,GET 请求被视为已接受,例如POST 我收到正确的405 状态代码。
现在我想介绍自定义组合注解,而不是在每个方法中都有相同的注解。
我的自定义注释看起来像,
@RequestMapping(
consumes = MimeTypeUtils.APPLICATION_JSON_VALUE,
produces = MimeTypeUtils.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Get {}
因此,我将方法更改为
@Get
@RequestMapping(value = "/users")
public UserResponse retrieveUsers() {
return new UserResponse();
}
在这种情况下,我可以看到我发送给/users 的任何类型的请求都得到了正确的处理。例如,即使我做POST,我也会看到响应。所以@RequestMapping 不能正常工作。
我在这里做错了什么?是否可以使用自定义组合注释使控制器正常运行?
【问题讨论】:
-
你为什么认为你的
@Get会这样工作? -
为什么不呢?实际上它正在工作,但不正确。例如,至少它会正确返回状态代码。我假设当我输入
@RequestMapping(value = "/users")时,它实际上覆盖了我的自定义注释中的映射,因为@Get中的另一个注释实际上正在工作。 -
您是否尝试将@RequestMapping 与一个注解结合起来,看看是否能解决问题?
-
为什么不让您的
@Get注释接受value并为您的value使用@RequestMapping,这样您就不必将它们分开。
标签: java spring spring-mvc annotations