SpringBoot中使用切面实现的日志记录

导入maven依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

定义注解

  • InsertLog.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InsertLog {
    String value() default "";
}
  • UpdateLog.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UpdateLog {
    String value() default "";
}
  • DeleteLog.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DeleteLog {
    String value() default "";
}

定义切面

  • AnnocationPointcut.java
@Component
@Aspect
@Slf4j
public class AnnocationPointcut {

    @Pointcut("@annotation(com.annocation.InsertLog)")
    public void insertLogPointcut(){}

    @Pointcut("@annotation(com.annocation.DeleteLog)")
    public void deleteLogPointcut(){}

    @Pointcut("@annotation(com.annocation.UpdateLog)")
    public void updateLogPointcut(){}

    @After("insertLogPointcut()")
    public void logInsert(JoinPoint jp){
        Object[] args = jp.getArgs();
        log.info("新增数据:" + args[0].toString());
    }

    @After("deleteLogPointcut()")
    public void logDelete(JoinPoint jp){
        Object[] args = jp.getArgs();
        log.info("删除数据:" + args[0].toString());
    }

    @After("updateLogPointcut()")
    public void logUpdate(JoinPoint jp){
        Object[] args = jp.getArgs();
        log.info("更新数据:" + args[0].toString());
    }

}

使用

例如插入日志。在插入方法上添加注解,会在插入结束后,把参数记录下来。

@Transactional(rollbackFor = Exception.class)
@Override
@InsertLog
public Result<List<InsReceiptResult>> insReceipt(InsReceiptParam param) {
    ...
}

扩展

1、PointCut的表达式标签

  • execution:用于匹配方法执行的连接点
  • within:用于匹配指定类型内的方法执行
  • this:用于匹配当前AOP代理对象类型的执行方法;注意是AOP代理对象的类型匹配,这样就可能包括引入接口也* 类型匹配
  • target:用于匹配当前目标对象类型的执行方法;注意是目标对象的类型匹配,这样就不包括引入接口也类型匹配
  • args:用于匹配当前执行的方法传入的参数为指定类型的执行方法
  • @within:用于匹配所以持有指定注解类型内的方法
  • @target:用于匹配当前目标对象类型的执行方法,其中目标对象持有指定的注解
  • @args:用于匹配当前执行的方法传入的参数持有指定注解的执行
  • @annotation:用于匹配当前执行方法持有指定注解的方法
  • bean:Spring AOP扩展的,AspectJ没有对于指示符,用于匹配特定名称的Bean对象的执行方法
    10种标签组成了12种用法,关于具体的用法,可以参考@Pointcut 的 12 种用法,你知道几种?

2、JoinPoint和ProceedingJoinPoint

  • JoinPoint:在除了@Around以外使用。(@Befor、@After、@AfterReturning、@AfterThrowing)

  • ProceedingJoinPoint:在@Around中使用

作用

  • Object[] getArgs:返回目标方法的参数
  • Signature getSignature:返回目标方法的签名
  • Object getTarget:返回被织入增强处理的目标对象
  • Object getThis:返回AOP框架为目标对象生成的代理对象
  • … …
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值