使用多个使用和生成 application/json
的 Spring Controller ,我的代码充满了长注释,例如:
@RequestMapping(value = "/foo", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
有没有办法用 consumes
和 produces
的 default 值生成“复合/继承/聚合”注释,这样我可以改为这样写:
@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)
我们如何定义像上面的 @JSONRequestMapping
这样的东西?注意 value
和 method
传入就像 @RequestMapping
一样,也可以传入 consumes
或 produces
如果默认值不合适。
我需要控制要返回的内容。我想要 produces
/consumes
注释方法,以便获得适当的 Content-Type
header 。
最佳答案
从 Spring 4.2.x 开始,您可以创建自定义映射注释,使用 @RequestMapping
作为元注释。所以:
Is there a way to produce a "composite/inherited/aggregated" annotation with default values for consumes and produces, such that I could instead write something like:
@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;
}
您可以在 spring 的 javadoc 中阅读有关 AliasFor
的更多信息。和 github wiki .
关于java - 用于生成和使用 JSON 的 Controller 的 Spring RequestMapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35123835/
相关文章:
json - angularjs - ng-重复 : access key and value fr
php - 如何防止 json_encode() 删除包含无效字符的字符串
json - 如何强制将请求正文解析为纯文本而不是 Express 中的 json?
javascript - Javascript对象和JSON对象有什么区别
javascript - 未捕获的类型错误 : Cannot read property 'owne
PHP json_encode - JSON_FORCE_OBJECT 混合对象和数组输出