AOP以注解作为切点的使用

主要是想可以通过在方法上或者类上添加注解以达到增强的作用
1.以下主要是作用在方法上的
定义注解

package com.winning;
 
 
 
import java.lang.annotation.*;
 
 
 
/**
* @author lmx
* @date 2020/9/10 4:41 下午
* 接口切点注解,用于标记需要计量计次的接口
*/
 
@Retention(RetentionPolicy.RUNTIME)
 
@Target(ElementType.METHOD)
 
@Documented
 
public @interface WinControllerPointCut {
 
}

创建切面类

package com.winning;
 
 
 
import lombok.extern.slf4j.Slf4j;
 
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.Pointcut;
 
import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
import org.springframework.scheduling.annotation.Async;
 
import org.springframework.stereotype.Component;
 
import org.springframework.web.context.request.RequestContextHolder;
 
import org.springframework.web.context.request.ServletRequestAttributes;
 
 
 
import javax.servlet.http.HttpServletRequest;
 
import java.util.Arrays;
 
 
 
/**
* @author lmx
* @date 2020/9/10 3:57 下午
*/
 
@Slf4j
 
@Aspect
 
@EnableAspectJAutoProxy
 
@Component
 
public class AopConfig {
 
 
 
    /**
     * 定义切点
     * 该切点指向某个包,因此要求对应包内只有接口的方法,业务方法请分离到业务层
     * 使用@annotation指定切点为 自定义注解接口com.winning.WinControllerPointCut
     */
 
    @Pointcut("@annotation(com.winning.WinControllerPointCut)")
 
    public void winPointCut() {
 
    }
 
 
 
    @Async
 
    @Before("winPointCut()")
 
    public void beforeCall(JoinPoint joinPoint) {
 
        //前置通知-业务,入参需要切点方法定义好
 
        ServletRequestAttributes attributes =
 
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 
        HttpServletRequest request = attributes.getRequest();
 
 
 
        log.info("before-接口路径:{}", request.getRequestURL().toString());
 
        log.info("before-请求方式:{}", request.getMethod());
 
        log.info("before-类方法:{}" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
 
        log.info("before-请求参数 : {} " + Arrays.toString(joinPoint.getArgs()));
 
    }
 
 
 
    @Async
 
    @AfterReturning(pointcut = "winPointCut()", returning = "resp")
 
    public void calcNetflow(Object resp) {
 
        //后置通知-业务,入参需要切点方法定义好
 
        ServletRequestAttributes attributes =
 
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 
        HttpServletRequest request = attributes.getRequest();
 
        log.info("afterReturning-接口路径:{}", request.getRequestURL().toString());
 
    }
 
 
 
}
 

在方法上使用注解
在这里插入图片描述
结果:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值