Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@RestControllerAdvice vs @ControllerAdvice

Tags:

spring

  • What are the major difference between @RestControllerAdvice and @ControllerAdvice ??
  • Is it we should always use @RestControllerAdvice for rest services and @ControllerAdvice MVC ?
like image 255
Om. Avatar asked Mar 30 '17 17:03

Om.


People also ask

What is difference between @RestControllerAdvice and @ControllerAdvice?

The differences between @RestControllerAdvice and @ControllerAdvice is : @RestControllerAdvice = @ControllerAdvice + @ResponseBody . - we can use in REST web services. @ControllerAdvice - We can use in both MVC and Rest web services, need to provide the ResponseBody if we use this in Rest web services.

What is @ControllerAdvice in spring boot?

@ControllerAdvice is a specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and similar.

What is @RestControllerAdvice?

The @RestControllerAdvice annotation is specialization of @Component annotation so that it is auto-detected via classpath scanning. It is a kind of interceptor that surrounds the logic in our Controllers and allows us to apply some common logic to them.

What is @controller and @RestController?

@Controller is used to mark classes as Spring MVC Controller. @RestController annotation is a special controller used in RESTful Web services, and it's the combination of @Controller and @ResponseBody annotation. It is a specialized version of @Component annotation.


2 Answers

@RestControllerAdvice is just a syntactic sugar for @ControllerAdvice + @ResponseBody, you can look here.

Is it we should always use @RestControllerAdvice for rest services and @ControllerAdvice MVC?

Again, as mentioned above, @ControllerAdvice can be used even for REST web services as well, but you need to additionally use @ResponseBody.

like image 112
developer Avatar answered Sep 19 '22 21:09

developer


In addition, we can just understand it as:

@RestControler = @Controller + @ResponseBody

@RestControllerAdvice = @ControllerAdvice + @ResponseBody.

Keeping in mind that @RestControllerAdvice is more convenient annotation for handling Exception with RestfulApi.

Example os usage:

@RestControllerAdvice public class WebRestControllerAdvice {      @ExceptionHandler(CustomNotFoundException.class)   public ResponseMsg handleNotFoundException(CustomNotFoundException ex) {     ResponseMsg responseMsg = new ResponseMsg(ex.getMessage());     return responseMsg;   } } 

In that case any exception instanceOf CustomNotFoundException will be thrown in body of response.

Example extracted here: https://grokonez.com/spring-framework/spring-mvc/use-restcontrolleradvice-new-features-spring-framework-4-3

like image 43
Eddy Bayonne Avatar answered Sep 20 '22 21:09

Eddy Bayonne