0

Small question regarding

@ResponseBody and @XXXMapping([...]  produces = MediaType.APPLICATION_JSON_VALUE)

Are they achieving the exact same thing?

Having the two together is redundant?

If no, what are the differences?

If yes, which one should be preferred?

Having the two together can bring anything positive? Any use case where we should have the two together?

Thank you

PatPanda
  • 3,644
  • 9
  • 58
  • 154

2 Answers2

1

@ResponseBody is generally used with @Controller for an ajax endpoint to let spring know you aren't rendering an html page, you want to return json or if you configure it, xml, etc. If you are using an @RestController it's not necessary. This is sort of a duplicate of this but I guess it's kind of different ‍♀️

DCTID
  • 1,277
  • 9
  • 13
0

Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST)

The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

Suppose we have a custom Response object:

public class ResponseTransfer {
    private String text; 
    
    // standard getters/setters
}
Next, the associated controller can be implemented:

@Controller
@RequestMapping("/post")
public class ExamplePostController {
 
    @Autowired
    ExampleService exampleService;
 
    @PostMapping("/response")
    @ResponseBody
    public ResponseTransfer postResponseController(
      @RequestBody LoginForm loginForm) {
        return new ResponseTransfer("Thanks For Posting!!!");
     }
}

In the developer console of our browser or using a tool like Postman, we can see the following response:

{"text":"Thanks For Posting!!!"} Remember, we don't need to annotate the @RestController-annotated controllers with the @ResponseBody annotation since Spring does it by default

let's implement a new method, mapped to the same /content path, but returning XML content instead:

@PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ResponseTransfer postResponseXmlContent(
  @RequestBody LoginForm loginForm) {
    return new ResponseTransfer("XML Content!");
}