spring aop unified daily and exception handling

  • AOP is a technology that achieves unified maintenance of program functions through pre-compilation and runtime dynamic agents. AOP reduces the coupling of various parts of the business logic and improves the reusability of the program.
  • Why use AOP?
    The code we write will inevitably have some running errors. Usually, we need to wrap the error and cannot directly return the exception information to the front end.
    But our front end is prone to bloat, like I wrote inside the company
 @GetMapping(value = "kmp")
  public BaseResponse kmp(@RequestParam String big, @RequestParam String small) {
    logger.info("kmp request,big=%s,small=%s", big, small);
    BaseResponse baseResponse = new BaseResponse();
    try {
      baseResponse.result = analyticsService.stringIndex(big, small);
    } catch (Exception e) {
      logger.info("kmp error,error=%s", e);
      return new BaseResponse(BaseError.FAIL);
    }
    logger.info("kmp response,result=%s", baseResponse);
    return baseResponse;
  }

These codes seem to be very bloated, and I found that there are a lot of error messages in it, but in fact it only executes a method:

baseResponse.result = analyticsService.stringIndex(big, small);

Seems like a lot of work.

  • Next we can use AOP to solve this kind of problem
    (1) Environment configuration
    Add dependent packages to pom.xml
<dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjweaver</artifactId>
     <version>1.8.13</version>
</dependency>

(2) How to use AOP
We modify the above method:

@GetMapping(value = "kmp")
public Object kmp(@RequestParam String big, @RequestParam String small) {
  return analyticsService.stringIndex(big, small);
}

Transformed to simply call the method and return directly.
So the question is, what about our logs? What about our exception handling?
we can do it in the aspect

@Aspect
@Component
public class ExceptionAspect {

  private Logger logger = LoggerFactory.getLogger(this.getClass());

  /**
   * Before the method call, print the input parameters
   */
  @Before(value = "execution(public * com.huyan.demo.controller.AnalyticsController.*(..))")
  public void before(JoinPoint joinPoint) {
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = joinPoint.getSignature().getName();
    Object[] args = joinPoint.getArgs();
    StringBuilder params = new StringBuilder();
    for (Object arg : args) {
      params.append(arg).append(" ");
    }
    logger.info(className + "of" + methodName + "The input is:" + params.toString());
  }

  /**
   * Process monitoring, return the packaged error message after catch ing the exception, and print the log
   */
  @Around(value = "execution(public * com.huyan.demo.controller.AnalyticsController.*(..))")
  public BaseResponse catchException(ProceedingJoinPoint joinPoint) {
    try {
      BaseResponse baseResponse = new BaseResponse(BaseError.SUCCESS);
      baseResponse.result = joinPoint.proceed();
      return baseResponse;
    } catch (Throwable e) {
      String className = joinPoint.getTarget().getClass().getName();
      String methodName = joinPoint.getSignature().getName();
      logger.warn("exist" + className + "of" + methodName + ", an exception occurred:" + e);
      return new BaseResponse(BaseError.FAIL);
    }
  }

  /**
   * After returning, print out the parameters
   */
  @AfterReturning(value = "execution(public * com.huyan.demo.controller.AnalyticsController.*(..))", returning = "returnVal")
  public void afterReturin(JoinPoint joinPoint, Object returnVal) {
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = joinPoint.getSignature().getName();
    logger.info(className + "of" + methodName + "The result is:" + returnVal.toString());
  }
}

Seeing the above information, you can see that the value in the annotation is the range covered by our aspect. Use execution expressions to define pointcuts.

(3)AOP advantage
Seeing this aspect class, we can clearly see that the exception handling class of this method is unified into the exception handling class, which greatly reduces the amount of code. Makes the business logic of the business layer look clearer.

(4) Other application scenarios of AOP
Performance monitoring, access statistics and authorization verification are also classic scenarios of AOP

It is found that the scope of the file in which we can perform this processing, or the annotation we define ourselves, and then let the annotation be placed on the method to make the processing take effect.

Tags: Spring

Posted by gplaurin on Tue, 03 May 2022 15:34:20 +0300