Advising controllers可以包含
@ExceptionHandler-annotated
@InitBinder-annotated
@ModelAttribute-annotated
Those methods in an @ControllerAdvice-annotated class are applied globally across
all @RequestMapping-annotated methods on all controllers in an application.
说明他可以用于织如,或者说横切所有的@RequestMapping-annotated methods
例如用它来横切异常:
package com.springmvc.error;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import com.google.common.base.Throwables;
/**
* General error handler for the application.
*/
@ControllerAdvice
class ExceptionHandler {
/**
* Handle exceptions thrown by handlers.
*/
@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
public ModelAndView exception(Exception exception, WebRequest request) {
ModelAndView modelAndView = new ModelAndView("error/general");
modelAndView.addObject("errorMessage", Throwables.getRootCause(exception));
return modelAndView;
}
}
用它来抓取异常,而不必写try()catch(){}!