Spring MVC controller ignores “consumes” property

2019-09-18 15:52发布

问题:

I have the controller bellow:

@RestController
@RequestMapping(value = "/v1/mail", consumes = {APPLICATION_JSON_VALUE})
@ResponseStatus(OK)
public class MailController {

    private CoreOutRestAdapter coreAdapter;

    @Autowired
    public MailController(CoreOutRestAdapter coreAdapter) {
        this.coreAdapter = coreAdapter;
    }

    @RequestMapping(method = POST)
    public void sendMail(@RequestBody @Validated Mail mail) {
        coreAdapter.sendMail(mail);
    }

}

and jackson-databind 2.3.2 in classpath. But if I send POST request with Content-Type: application/json, returned response contains 415 status (Unsupported Media Type). I don't understand why controller ignores "consumes" property in @RequestMapping annotation. How can I fix this? Also, the rest of project you can find at github https://github.com/f1xmAn/scail

回答1:

Below is the working example from my application code.

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/abc")
public class ABC {


    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String getRequest(@RequestBody XYZ xyz) {

        return "success";
   }


回答2:

I forgot annotate config with @EnableWebMvc. After annotating controller works fine.