SpringBoot基础系列:切面

1 @PointCut

  • 默认拦截所有 @Pointcut(“execution(* com.company.controller….(…)) || execution(* com.company…exception….(…))”)中加载的包执行情况。
  • @Pointcut("@annotation(com.company.annotation.MyAnnotation)")无法应用于普通方法
package com.company.microserviceuser.aop;

import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import ******;

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.stream.Stream;

/**
 * 日志拦截.
 *  
 * @author xindaqi 
 * @since 2020-10-23
 */
@Aspect 
@Component
public class ApiCallLog {

    @Resource
    private AnnotationUtil annotationUtil;

    private static ThreadLocal<Long> startTime = new ThreadLocal<>();

    private Logger logger = LoggerFactory.getLogger(ApiCallLog.class);

    /**
     * 方法切入点,执行对应的方法
     * 1. execution : 表达式主体
     * 2. * :任意类型返回值
     * 3. com.company.web.controller : AOP切片的包名
     * 4. .. :当前包及子包
     * 5. * : 类名,*表示所有类
     * 6. .*(..) : 方法名,*表示任何方法名,..:任何参数类型
     */
    @Pointcut("execution(* com.company.controller..*.*(..)) || execution(* com.company..exception..*.*(..))")
    public void callLog() {
        logger.info("Pointcut");
    }

    /**
     * 切入方法执行前的方法
     * 
     * @param joinPoint 反射接口(Interface)
     * @throws Exception
     */
    @Before("callLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        logger.info("===Api call aspect do before.===");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("URL: {}", request.getRequestURI());
        logger.info("HTTP METHOD: {}", request.getMethod());
        logger.info("IP: {}", request.getRemoteAddr());
        logger.info("Class METHOD: {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("Class name:{}", joinPoint.getTarget().getClass().getName());
        Enumeration<String> enums = request.getParameterNames();
        while(enums.hasMoreElements()) {
            String paramName = enums.nextElement();
            logger.info("Parameter name: {}", request.getParameter(paramName));
        }
    }

    /**
     * 切入方法执行结束后的方法
     */
    @After("callLog()")
    public void doAfter(JoinPoint joinPoint) {
        logger.info("===Api call aspect do after.===");

    }

    /**
     * 切入方法返回后执行方法
     */
    @AfterReturning(value = "callLog()", returning = "returnValue")
    public void doAfterReturing(JoinPoint joinPoint, Object returnValue) throws Exception {
        if(joinPoint.getArgs().length != 0){
            Stream.of(joinPoint.getArgs()).forEach(s -> annotationUtil.desensitization(s));
            annotationUtil.desensitization(joinPoint.getArgs()[0]);
        }
        logger.info("ARGS: {}", joinPoint.getArgs());
        long costTime = System.currentTimeMillis() - startTime.get();
        logger.info("返回值:{}", returnValue);
        logger.info("Time spending: {}ms", costTime);
        logger.info("===Api call aspect do afterReturing.===");
        startTime.remove();
    }
}

2 @Around

  • 定义方法注解,即在方法上使用该注解,会执行注解的逻辑,应用于方法执行时间计算等场景。
  • 使用@Around注解拦截的方法注解,可以应用于所有方法
  • @Around环绕增强,相当于MethodInterceptor,CGLib代理,代理普通类,因此可以使用反射获取类的方法,使用该注解可以拦截任意级别的方法

2.1 注解

package com.company.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 方法注解
 * 
 * @author xindaqi
 * @since 2020-12-26
 */
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    String name() default "xindaqi";

}

2.2 注解拦截

package com.company.microserviceuser.aop;

import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.company.microserviceuser.utils.AnnotationUtil;

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Around;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.stream.Stream;

import com.company.microserviceuser.dto.LoginInputDTO;
/**
 * 自定义方法切面.
 *  
 * @author xindaqi 
 * @since 2020-10-23
 */
@Aspect 
@Component
public class MyAop {

    @Resource
    private AnnotationUtil annotationUtil;

    private static ThreadLocal<Long> startTime = new ThreadLocal<>();

    private Logger logger = LoggerFactory.getLogger(ApiCallLog.class);

    @Around("@annotation(com.company.annotation.MyAnnotation)")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        // 方法执行前
        logger.info("===我是使用了MyAnnotation注解的方法:{}===", methodName);
        startTime.set(System.currentTimeMillis());
        Object obj = joinPoint.proceed();
        // 方法执行后
        long costTime = System.currentTimeMillis() - startTime.get();
        startTime.remove();
        logger.info("方法:{}执行时间:{}ms", methodName, costTime);
        return obj;
    }   
    
}

2.3 使用注解的方法样例

package com.company.utils;

import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.company.annotation.MyAnnotation;

/**
 * @author xindaqi
 * @since 2020-10-26
 */
@Component
public class TimeProcessUtil {

    private static final Logger logger = LoggerFactory.getLogger(TimeProcessUtil.class);

    @MyAnnotation
    public String timeGenerateFromPattern(String timePattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(timePattern);
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch(Exception e) {
            logger.error("时间异常", e);
        } finally {
            logger.info("时间转换");
        }
        
        return LocalDateTime.now().format(dtf);
    }
    
}

调用timeGenerateFromPattern()方法时会触发注解@MyAnnotation的逻辑。

3 小结

序号注解描述
1@PointCut适用于拦截指定包的类及方法,不适用于定义方法级别的注解
2@Around适用于任何方法拦截,相当于MethodInterceptor,CGLib代理,代理普通类,因此可以使用反射获取类的方法,使用该注解可以拦截任意级别的方法

【参考文献】
[1]https://www.jianshu.com/p/ca9eb94e71f1
[2]https://blog.csdn.net/u012843873/article/details/78624391
[3]https://www.cnblogs.com/pcheng/p/7099385.html
[4]https://blog.csdn.net/reee112/article/details/84937386

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值