常见用法:
- 配合 @ExceptionHandler 实现全局异常处理
- 配置 @InitBinder 实现自定义全局类型转换器
官方文档:https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-initbinder
1、全局异常处理器:
@ControllerAdvice@Order(0) // 定义优先级:数值越小,优先级越高public class MyRuntimeExceptionHandler {@ExceptionHandler(RuntimeException.class)public ResponseEntity<String> runtimeExceptionHandler(RuntimeException ex) {// 将服务器异常信息转换成json格式抛出去return ResponseEntity.status(HttpStatus.ACCEPTED).header("Content-Type","application/json;charset=utf-8").body(ex.getMessage());}@ExceptionHandler(Throwable.class)public ResponseEntity<String> exception(Throwable t){return ResponseEntity.status(404).header("Content-Type","application/json;charset=utf-8").body(t.getMessage());}}
2、绑定全局类型转换器
public class MyDateFormatter {// 这里value参数用于指定需要绑定的参数名称,如果不指定,则会对所有的参数进行适配,// 只有是其指定的类型的参数才会被转换@InitBinderpublic void initBinder(WebDataBinder binder) {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");dateFormat.setLenient(false);binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));}}
测试:
@RequestMapping("/str2")public void demo(Date date) {System.out.println(date);}
