“This is the first day of my participation in the Gwen Challenge in November. See details of the event: The last Gwen Challenge in 2021”.
1, the preface
As the name of the annotation indicates, this is an annotation that is related to the aspect. In fact, we all know that the aspect annotation must have a scope, and the annotation of the aspect class can only implement the aspect operation within its scope. So what’s the scope of RestCntrollerAdvice?
2. @RestControllerAdvice notes
As mentioned above, each facet annotation has its own scope, and this one is no exception. The scope of RestControllerAdvice is: All classes in a single project that use RequestMapping (e.g. PostMapping) are under his control. RestControllerAdvice is under his control. So what does this RestControllerAdvice annotation do? It seems that based on his name we can only see that this is a section annotation applied to the Controller layer and nothing else. In fact, this annotation needs to be used in conjunction with other annotations to make sense. It is meaningless to use this annotation alone. Here is what annotations can be used in conjunction with this annotation
2.1 @ ExceptionHandler
RestControllerAdvice+ExceptionHandler the combination of these two annotations is used for global exception handling of the project, which is what I use in my current project. Once an exception occurs in the project, we enter the method that uses the ExceptionHandler annotation from the RestControllerAdvice annotation class, where we can handle the global exception and output the exception information to the specified location. And to put all the error messages, here is the sample code:
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
// Custom exception handling methods
@ExceptionHandler(WinningException.class)
public Response winningException(WinningException e){
Response response = Response.getErrResponse(e);
return response;
}
// Other exceptions are returned to the front-end processing
@ExceptionHandler(Exception.class)
public Response otherException(Exception e){
e.printStackTrace();
log.error(e.getMessage());
Response response = Response.getErrResponse(e);
returnresponse; }}Copy the code
To explain part of this code, SLf4J is a log annotation that returns to the front end according to different error types and edit the text according to each error type, so that we actually complete control of the global exception message. RestControllerAdvice+ExceptionHandler is the correct way to do this.
2.2 InitBinder annotations and ModelAttribute Annotations
These two annotations can also be used with RestControllerAdvice, so what do they do?
- The InitBinder annotation is used to bind parameters passed by the front end separately
- ModelAttribute: Gets the InitBinder binding parameters and binds them to properties
@Controller
@RequestMapping("/test")
public class TestController {
// Bind variable names and attributes, and encapsulate arguments into classes
@InitBinder("user")
public void initBinderUser(WebDataBinder binder) {
binder.setFieldDefaultPrefix("user.");
}
// Bind variable names and attributes, and encapsulate arguments into classes
@InitBinder("addr")
public void initBinderAddr(WebDataBinder binder) {
binder.setFieldDefaultPrefix("addr.");
}
@RequestMapping("/test")
@ResponseBody
public Map<String,Object> test(HttpServletRequest request,@ModelAttribute("user") User user,@ModelAttribute("addr") Addr addr){
Map<String,Object> map=new HashMap<String,Object>();
map.put("user", user);
map.put("addr", addr);
return map;
}
Copy the code
If you don’t understand, I recommend reading his blog: SpringMvc @initBinder form to receive multiple objects with precise binding.
3 ControllerAdvice与RestContollerAdvice
At first glance, these two annotations look similar, except for a Rest. What are the similarities and differences between them? RestController advice =ControllerAdvice+ResponseBody So it’s pretty clear what ResponseBody is doing is converting the parameters that are returned to the front end into JSON format, and basically interacting with the front end with JSON data. So the difference between ControllerAdvice and RestContollerAdvice is that one returns data in JSON format to the front end, and the other returns objects, and most projects now interact with the front end in JSON format, So the advice is to use annotations like RestControllerAdvice and RestController
4 How is GlobalExceptionHandler loaded
ExceptionHandlerExceptionResolver class implements the InitializingBean interface surface is initialized at startup ExceptionHandlerExceptionResolver bean when loaded.
All initExceptionHandlerAdviceCache first found in the container with @ ControllerAdvice annotation class (@ RestControllerAdvice annotations are @ ControllerAdvice and @ ResponseBody Compositional notes). You can see our custom GlobalExceptionHandler found here.
Then iterate over all adviceBeans, converts these adviceBeans ExceptionHandlerMethodResolver, transformation in the process of scanning each ControllerAdvice @ ExceptionHandler annotation methods, ExceptionHandler is used to handle the Exception types, which may be multiple. ExceptionType is used as key and Method is used as value to cache the ExceptionHandler in mappedMethods map.
Then add ExceptionHandlerExceptionResolver adviceBean exceptionHandlerAdviceCache caching in this map. Finally exceptionHandlerAdviceCache data in the following