Loading...

Spring Boot - ControllerAdvice, RestControllerAdvice, ResponseBody | Simple Programming

62538 590________

Welcome to Simple Programming

Today lets us look at how @ControllerAdvice and @RestContollerAdvice works

In our previous example we looked at @ExceptionHandler

The drawback in using @ExceptionHandler directly in a controller class is - it will be active only inside that controller

If there are multiple controllers, we need to segregate the exceptions handlers into a common class so that it looks elegant and easy to maintain in future.

@ControllerAdvice does that job easily.

When you use @ControllerAdvice, your response will be returned as a plain JSON element.

That is because there is no @ResponseBody Annotation in the method

If you annotate a method with @ResponseBody, spring will try to convert its return value and write it to the http response automatically

If you application is a restful service, then you can change this Controller Advice to RestController Advice

RestController Advice combines both @Controller Advice and @ResponseBody in it

so we don’t need to explicitly annotate the method with @ResponseBody

The same goes for @Controller and @RestControllers, because @ResponseBody is done by default when you use @RestController Advice.

Here are some interview Questions,
What is the difference between @ControllerAvice and @RestControllerAdvice

What is the difference between @Controller and @RestController

How will you handle Exception in the SpringBoot Application

What is the disadvantage of using @ExceptionHandler directly in the Controller Class

コメント