Spring RequestMapping for controllers that produce and consume JSON

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

    You shouldn't need to configure the consumes or produces attribute at all. Spring will automatically serve JSON based on the following factors.

    • The accepts header of the request is application/json
    • @ResponseBody annotated method
    • Jackson library on classpath

    You should also follow Wim's suggestion and define your controller with the @RestController annotation. This will save you from annotating each request method with @ResponseBody

    Another benefit of this approach would be if a client wants XML instead of JSON, they would get it. They would just need to specify xml in the accepts header.

提交回复
热议问题