@RestControllerAdvice vs @ControllerAdvice

后端 未结 3 1846
孤独总比滥情好
孤独总比滥情好 2020-12-14 07:03
  • What are the major difference between @RestControllerAdvice and @ControllerAdvice ??
  • Is it we should always use @RestControllerAdvice for rest services and @C
3条回答
  •  轮回少年
    2020-12-14 07:42

    In addition, we can just understand it as:

    @RestControler = @Controller + @ResponseBody

    @RestControllerAdvice = @ControllerAdvice + @ResponseBody.

    Keeping in mind that @ControllerAdvice 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

提交回复
热议问题