Spring RequestMapping for controllers that produce and consume JSON

后端 未结 5 1279
野的像风
野的像风 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:37

    The simple answer to your question is that there is no Annotation-Inheritance in Java. However, there is a way to use the Spring annotations in a way that I think will help solve your problem.

    @RequestMapping is supported at both the type level and at the method level.

    When you put @RequestMapping at the type level, most of the attributes are 'inherited' for each method in that class. This is mentioned in the Spring reference documentation. Look at the api docs for details on how each attribute is handled when adding @RequestMapping to a type. I've summarized this for each attribute below:

    • name: Value at Type level is concatenated with value at method level using '#' as a separator.
    • value: Value at Type level is inherited by method.
    • path: Value at Type level is inherited by method.
    • method: Value at Type level is inherited by method.
    • params: Value at Type level is inherited by method.
    • headers: Value at Type level is inherited by method.
    • consumes: Value at Type level is overridden by method.
    • produces: Value at Type level is overridden by method.

    Here is a brief example Controller that showcases how you could use this:

    package com.example;
    
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.*;
    
    @RestController
    @RequestMapping(path = "/", 
            consumes = MediaType.APPLICATION_JSON_VALUE, 
            produces = MediaType.APPLICATION_JSON_VALUE, 
            method = {RequestMethod.GET, RequestMethod.POST})
    public class JsonProducingEndpoint {
    
        private FooService fooService;
    
        @RequestMapping(path = "/foo", method = RequestMethod.POST)
        public String postAFoo(@RequestBody ThisIsAFoo theFoo) {
            fooService.saveTheFoo(theFoo);
            return "http://myservice.com/foo/1";
        }
    
        @RequestMapping(path = "/foo/{id}", method = RequestMethod.GET)
        public ThisIsAFoo getAFoo(@PathVariable String id) {
            ThisIsAFoo foo = fooService.getAFoo(id);
            return foo;
        }
    
        @RequestMapping(path = "/foo/{id}", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
        public ThisIsAFooXML getAFooXml(@PathVariable String id) {
            ThisIsAFooXML foo = fooService.getAFoo(id);
            return foo;
        }
    }
    

提交回复
热议问题