由于多个Spring控制器消耗并产生application/json个,我的代码中充满了长注释,比如:

    @RequestMapping(value = "/foo", method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)

有没有办法生成一个"复合/继承/聚合"注释,其中consumesproduces的值为default,这样我就可以编写如下内容:

    @JSONRequestMapping(value = "/foo", method = RequestMethod.POST)

How do we define something like @JSONRequestMapping above? Notice the value and method passed in just like in @RequestMapping, also good to be able to pass in consumes or produces if the default isn't suitable.

I need to control what I'm returning. I want the produces/consumes annotation-methods so that I get the appropriate Content-Type headers.

推荐答案

从4.2年春天开始.x、 可以使用@RequestMapping作为元注释来创建自定义映射注释.所以:

有没有一种方法可以产生"复合/继承/聚合"

@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)

是的,有这样一条路.您可以创建如下所示的元注释:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/json", produces = "application/json")
public @interface JsonRequestMapping {
    @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 {};
}

然后,您可以使用默认设置,甚至可以根据需要覆盖它们:

@JsonRequestMapping(method = POST)
public String defaultSettings() {
    return "Default settings";
}

@JsonRequestMapping(value = "/override", method = PUT, produces = "text/plain")
public String overrideSome(@RequestBody String json) {
    return json;
}

You can read more about AliasFor in spring's javadoc and github wiki.

Json相关问答推荐

使用JSONata将具有相同键的字典合并

Bash和echo命令出现意外结果

如何在Vega中使标记的符号在鼠标指针悬停时可点击

在MongoDB中检索某个月份和年份的JSON文档

Jolt-在数组列表中插入新的字段

使用 jolt 将对象数组转换为数组

颠簸转换问题

JOLT 获取带有动态键的数组

派生类的属性没有得到价值

使用 ConvertFrom-Json 后,Powershell 访问 JSON 中的嵌套对象

我无法在 Go - Gin 中解析日期/时间

序列化为json时如何忽略空列表?

Json.NET SerializeObject 转义值以防止 XSS

反序列化大型 json 对象的 JsonMaxLength 异常

如何通过 NSJSONSerialization 在 JSON 中包含空值?

将 JSON 对象推送到 localStorage 中的数组

as_json 没有在关联上调用 as_json

POST:在 url 本身中发送 post 请求

如何在 Python 中合并两个 json 字符串?

从 JSON 中 Select 不同的值