java 与@RequestMapping一起使用的自定义注解在Sping Boot 中不起作用

hzbexzde  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(187)

我创建了如下自定义注记

@Retention(RUNTIME)
@Target(METHOD)
@RequestMapping(consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = {
        MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
public @interface JsonPostMapping {
    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value() default {};

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

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

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

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

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

我有以下控制器

import com.config.requestmappings.JsonPostMapping;

@RestController
public class TestController {

    @JsonPostMapping(value = "/hello")
    public String hello() {
        return "Hi, how are you";
    }

}

hello API也被GET请求调用,我希望它只在POST请求时调用。

soat7uwm

soat7uwm1#

删除注解中method的别名,并使用@PostMapping代替@RequestMapping。在注解本身的正文中设置默认值。

@PostMapping
public @interface JsonPostMapping {
    // ...
    @AliasFor(annotation = PostMapping.class)
    String[] consumes() default { MediaType.APPLICATION_JSON_VALUE };

    @AliasFor(annotation = PostMapping.class)
    String[] produces() default { MediaType.APPLICATION_JSON_VALUE };
}

相关问题