您的当前位置:首页正文

AOP-4.1-Spring @Pointcut使用

2024-11-29 来源:个人技术集锦

一、使用

@Slf4j
@Aspect
@Component
public class ParamLogAspect {

    /**
     * 定义一个切入点
     */
    @Pointcut("execution(* com.x.*.controller.*Controller.*(..))")
    public void point() {
    }

    // 前置通知
    @Before(value = "point()")
    public void before(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestUrl = request.getRequestURL().toString();
        Map<String, String> parameterMap = new HashMap<>();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = signature.getParameterNames();
        Class<?>[] parameterTypes = signature.getParameterTypes();
        for (int i = 0; i < parameterNames.length; i++) {
            String parameterName = parameterNames[i];
            Class<?> parameterType = parameterTypes[i];
            if (HttpServletRequest.class.equals(parameterType)) {
                continue;
            }
            if (HttpServletResponse.class.equals(parameterType)) {
                continue;
            }
            Object arg = joinPoint.getArgs()[i];
            parameterMap.put(parameterName, JSON.toJSONString(arg));
        }
        log.info("请求url:{},参数:{},ip:{}", requestUrl, JSON.toJSONString(parameterMap), IpUtil.getIpAddr(req
显示全文