SpringAop @annotation\@Aspect练习

11 篇文章 0 订阅
1 篇文章 0 订阅

切面记录日志

切面类

@Slf4j
@Aspect
@Component
public class AspectForFeign {
    
    @Pointcut("execution(public * com.keke.remote..*Feign.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        log.info("@Around:开始执行目标方法:{}ms", start);
        Object result = null;
        try {
            result = joinPoint.proceed();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        long end = System.currentTimeMillis();
        log.info("@Around:结束执行目标方法:{}ms", end);
        //获取方法签名		
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String methodName = methodSignature.getName();
        log.info("方法名:{} 耗时:{}ms", methodName, end - start);
        //如果不返回result,则目标对象实际返回值会被置为null
        return result;
    }
   
  • 注意:返回结果如果不返回result,则目标对象实际返回值会被置为null

@Component

  • 需要将切面类配置为bean

@Aspect

  • 标记为切面类

@Pointcut

  • 需要表达式命名,而不需要在方法体内编写实际代码。
  execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?) 
修饰符匹配(modifier-pattern?)
例:puiblic
返回值匹配(ret-type-pattern)
可以为表示任何返回值,全路径的类名等
类路径匹配(declaring-type-pattern?)
*Feign代表以Feign结尾的类
方法名匹配(name-pattern)
*代表所有
参数匹配((param-pattern))
多个参数间用“,”隔开,各个参数也可以用 * 来表示匹配任意类型的参数,如(String)表示匹配一个String参数的方法;(*,String) 表示匹配有两个参数的方法,第一个参数可以是任意类型,而第二个参数是String类型;可以用(…)表示零个或多个任意参数
异常类型匹配(throws-pattern?)
?可选项

@Around

  • 环绕增强,@Pointcut和@Around联合使用等同于:
 @Around("execution(public * com.keke.remote..*Feign.*(..))")

切点拦截记录访问日志

拦截器数据源

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)//注解在方法上
public @interface ApiAccess{
}

拦截器业务实现代码

@Aspect
@Component
@Slf4j
public class ApiAccessAspect {

    @Pointcut("@annotation(com.keke.annotation.ApiAccess)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object apiAccessAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        log.info("url:{}被访问了.....",request.getRequestURL().toString());
        return joinPoint.proceed(joinPoint.getArgs());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值