首页 > 其他 > 详细

@ConTrollerAdvice的使用

时间:2017-08-05 23:29:47      阅读:1162      评论:0      收藏:0      [点我收藏+]

@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就可以访问了。

@ConTrollerAdvice的使用

原文:http://www.cnblogs.com/yimixiong/p/7291824.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!