从 Spring 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;
}
你可以在spring的javadoc和github wiki中阅读更多关于的信息。AliasFor