@RestControllerAdvice vs @ControllerAdvice

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


@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.

Tags:

Spring