@ConTrollerAdvice的使用
@ConTrollerAdvice,从名字上面看是控制器增强的意思。
在javaDoc写到
/**
* Indicates the annotated class assists a "Controller".
*
* <p>Serves as a specialization of {@link Component @Component}, allowing for
* implementation classes to be autodetected through classpath scanning.
*
* <p>It is typically used to define {@link ExceptionHandler @ExceptionHandler},
* {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
* methods that apply to all {@link RequestMapping @RequestMapping} methods.
*
* @author Rossen Stoyanchev
* @since 3.2
*/
也就是把@ControllerAdvice注解内部所有的@ExceptionHandler,@ InitBinderhe @ ModelAttribute应用到所有的@RequestMapping注解的方法里面去。
比较常用的场景,可以将异常处理器应用到所有的控制器中,而不是当个的控制器。
@RestControllerAdvice
public class ExecptionHanlerController {
@ExceptionHandler(value=Exception.class)
public String handleException(Exception e){
return "不要慌张,系统出现故障,请联系管理员!"+e.getMessage();
}
@ModelAttribute
public void addAttribute(Model model){
model.addAttribute("mess", "world");
}
}
@RestController
public class HelloController {
@RequestMapping("/home")
public String home(@ModelAttribute("mess")String message){
return "hello!"+message;
}
@RequestMapping("/ex")
public String getexception(){
throw new IllegalArgumentException("真的不知道说什么.....");
}
}
启动String Boot就可以访问了。