繁体   English   中英

Spring Controller:结合了Spring注释的自定义注释不起作用

[英]Spring Controller: Custom annotation with combined Spring annotations does not work

我有正常工作的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部分,而将所有其他属性保留为默认值。

我怀疑UserResponse#retrieveUsers上的@RequestMapping(value = "/users")替换了@Get接口上的@RequestMapping

查看是否可行:

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

    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value() default {};
}

@Get(value = "/users")
public UserResponse retrieveUsers() {
    return new UserResponse();
}

您可能对春季项目中的GetJson感兴趣。

请注意, @ AliasFor仅在Spring 4.2中发布。 在早期版本中不可用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM