注解@RestControllerAdvice
1、源码
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice {
@AliasFor("basePackages")
String[] value() default {};@AliasFor("value")
String[] basePackages() default {};Class<?>[] basePackageClasses() default {};
Class<?>[] assignableTypes() default {};
Class<? extends Annotation>[] annotations() default {};
}
2、它通常用于定义@ExceptionHandler, @InitBinder 和 @ModelAttribute 适用于所有@RequestMapping方法的方法。
案例:
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器。
*
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
log.info("binder.getFieldDefaultPrefix {}",binder.getFieldDefaultPrefix());
log.info("binder.getFieldMarkerPrefix {}",binder.getFieldMarkerPrefix());
}
/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值。
* @param model
*/
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("author", "harry");
}
/**
* 异常处理
* @param e
*/@ExceptionHandler(BaseException .class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public HR apiExceptionHandler(BaseException e) {
log.error("Exception 异常抛出:{}", e);
return HR.fail(ex);
}}
3、自定义BaseException类@Getter
@Setterpublic class BaseException extends RuntimeException {
//todo
}