Spring RequestMapping for controllers that produce and consume JSON

后端 未结 5 1312
野的像风
野的像风 2020-11-30 23:21

With multiple Spring controllers that consume and produce application/json, my code is littered with long annotations like:



        
5条回答
  •  甜味超标
    2020-11-30 23:43

    As of Spring 4.2.x, you can create custom mapping annotations, using @RequestMapping as a meta-annotation. So:

    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)
    

    Yes, there is such a way. You can create a meta annotation like following:

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

    Then you can use the default settings or even override them as you want:

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

提交回复
热议问题