Application of several spring annotations

 

Application of several spring annotations

 

 

(one)

@ControllerAdvice(assignableTypes=PayController.class)//equivalent to spring's post-processor execution notification, aop's surround notification

 

 

 

@ControllerAdvice(assignableTypes=PayController.class)

public class PayExceptionHandler {

 

@ExceptionHandler(Exception.class)

@ResponseBody

public String PaException(HttpServletRequest request, Exception ex){

return "rspCode=000001&rspMsg="+ex.getMessage();

}

 

}

 

 

 In the CommonExceptionHandler class annotated with @controllerAdvice, the handleStaffNotFound() method is annotated with @ExceptionHandler(StaffNotFoundException.class), which means that when the controller throws a StaffNotFoundException exception, it will delegate this method to handle it. 


One of the most useful scenarios for @controllerAdvice is to collect all @ExceptionHandler methods into one class, so that all exceptions can be handled consistently in one place. 

@ControllerAdvice By default, all exceptions thrown by the control will be processed in this class 
@ControllerAdvice(annotations = {PCInfoController .class}) configure the controller you need to intercept, 
@ControllerAdvice(basePackages = "com.demo") configure the path you need controller under

 

(two)

 

1. Controller, RestController common ground

 

     Are used to indicate whether a spring class can receive HTTP requests

2. Differences between Controller and RestController

 

     @Controller identifies a Spring class as a Spring MVC controller handler

 

     @RestController:  a convenience annotation that does nothing more than adding the@Controller and @ResponseBody annotations。 

     @RestController is a combination of @Controller and @ResponseBody, and the two annotations are combined.

     MVC's mapping method defaults to @responsebody

 

 

An example is as follows:

[html] view plain copy

@Controller  

@ResponseBody  

public class MyController { }  

  

@RestController  

public class MyRestController { }  

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326327370&siteId=291194637