Introduction of depend on

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
      <version>2.1.3. RELEASE</version>
    </dependency>
Copy the code

The breakthrough point

@RestController
@Params
public class JimDbController {

  @RequestMapping(value = "/aspect",method = {RequestMethod.GET})
  @SMSAndMailSender(smsContent = "Orange XXXXX")
  public GatewayResult<Boolean> aspectJController(@RequestBody PowerQuery powerQuery) {
    return new GatewayResult<>().buildSuccess(powerQuery.getPowerName().equals("Success")); }}Copy the code

Custom annotations

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Order(1)
public @interface Params {
  String value() default "";
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Order(2)
public @interface SMSAndMailSender {
  String value() default "";
  String smsContent() default "";
  String mailContent() default "";
  boolean isActive() default true;
  String subject() default "";
}
Copy the code

Normal execution

abnormal

Enhanced section class

@Aspect
@EnableAspectJAutoProxy
@Component
@Slf4j
@Order(2)
public class AdviceHandle {

  // Surround enhancement
  // Wrap notification is very powerful and can determine if and when the target method executes, if method parameters need to be replaced during execution, and if return values need to be replaced after execution.
  @Around("execution(* com.cool.controller.JimDbController.aspe*(..) )")
  public Object process(ProceedingJoinPoint point) throws Throwable {
    Object[] args = point.getArgs();
    log.info("Around parameters." + args.toString());
    Object proceed = point.proceed(args);
    String methodKey = point.toLongString();
    log.info("Around methodKey:" + methodKey);
    return proceed;
  }

  // Identifies a pre-enhanced method. @Within is an annotation for the class
  @Before("@within(com.cool.domain.Params)")
  public void permissionCheck(JoinPoint point) {
    log.info("Before:" + point.getSignature().getName());
    log.info("Before:" + point.getTarget().toString());
  }

  // Final enhancements are executed whether an exception is thrown or a normal exit.
  @After(value = "@annotation(com.cool.domain.SMSAndMailSender) && args(powerQuery)")
  public void after(JoinPoint joinPoint, PowerQuery powerQuery) {
    log.info("After parameters." +powerQuery);
  }

  // Post-enhancement, executed when the method exits normally
  @AfterReturning(value = "execution(* com.cool.controller.JimDbController.aspe*(..) )", returning = "returnValue")
  public void log(JoinPoint point, Object returnValue) {
    log.info("AfterReturning:" + Arrays.toString(point.getArgs()));
    log.info("AfterReturning:" + returnValue.toString());
  }

  //@annotation is an annotation for a method
  @AfterReturning(value = "@annotation(com.cool.domain.SMSAndMailSender)", returning = "re")
  public void afterReturn(JoinPoint join, Object re) {
    MethodSignature ms = (MethodSignature) join.getSignature();
    Method method = ms.getMethod();
    boolean active = method.getAnnotation(SMSAndMailSender.class).isActive();
    if(! active) {return;
    }
    String content = method.getAnnotation(SMSAndMailSender.class).smsContent();
    log.info("AfterReturning Information :" + content);
    log.info("AfterReturning value information :" + re);
  }

  // Exception throw enhancement
  @AfterThrowing(value = "@within(org.springframework.web.bind.annotation.RestController)", throwing = "ex")
  public void afterThrow(JoinPoint join, Throwable ex) {
    MethodSignature signature = (MethodSignature) join.getSignature();
    Method method = signature.getMethod();
    String subject = method.getAnnotation(SMSAndMailSender.class).subject();
    log.info(subject);
    log.info("Abnormal"+ ex.getMessage()); }}Copy the code

The same method is intercepted by multiple facets

Class through annotations @ the Order priority (digital) to determine or cut class implements org. Springframework. Core. The Ordered interface: implement the interface of int getOrder () method, the smaller the number the higher the priority.

Enhancements in a high-priority aspect class are always given higher priority than enhancements in a low-priority aspect class.

On “entering” the join point, the enhancement with the highest priority will be woven first (eg. Given two different aspect classes Before the enhancement, the one with the highest priority will be executed first); When “exiting” the join point, the highest-priority enhancement processing is woven in last (eg. Given two different aspect classes in After enhancement, the one with the highest priority will be executed. Eg. The section class Bean1 with priority 1 contains @before, and the section class Bean2 with priority 2 contains @around. Although @around has a higher priority than @before, the @before in Bean1 is woven first because the priority of Bean1 is higher than that of Bean2.

Other @ ControllerAdvice annotation

In Spring 3.2, @ControllerAdvice and @RestControllerAdvice annotations were added to define @ExceptionHandler, @initBinder, @ModelAttribute, Apply this to all @requestMapping, @postMapping, and @getMapping annotations.

  1. Exception handling
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandle(HttpRequest httpRequest,Exception ex) {
HashMap<String.Object> map = new HashMap<>();
map.put("100".100);
map.put("ex",ex.getMessage());
return map;
}
Copy the code
  1. Data binding
@ModelAttribute(name = "md")
public Map<String.Object> mydata() {
    HashMap<String.Object> map = new HashMap<>();
    map.put("age".99);
    map.put("gender"."Male");
    return map;
}
Copy the code
  1. Global data preprocessing
@InitBinder("date")
public void a(WebDataBinder binder) {
    binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}
Copy the code