2

I have a controller annotated as @RestController, so it automatically add @ResponseBody to all methods annotated with @RequestMapping. But if I use @ExceptionHandler annotation and return some response:

@ExceptionHandler
public @ResponseBody Response someHandler(Exception ex) { ... }

Can I remove @ResponseBody from handler? And If I use @ControllerAdvice is it possible to remove @ResponseBody annotation from it's handlers?

1 Answer 1

2

As of Spring 4.0, @ResponseBody annotation can also be added on the type level in which case it is inherited and does not need to be added on the method level. So, if you use @ResponseBody on Type Level, you do not need to use it on @RequestMappings and ExceptionHandlers.

Can I remove @ResponseBody from handler?

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. So, Yes you can remove it since @RestContorller adds a @ResponseBody on the type level.

And If I use @ControllerAdvice is it possible to remove @ResponseBody annotation from it's handlers?

No, you can't do that here unless you add a ResponseBody on the type level.

In both cases, if you return an instance of ResponseEntity as your return value, you won't need the ResponseBody.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.