使用 AOP(面向切面编程)和自定义注解实现日志记录

该文介绍了如何在SpringBoot中使用AOP来实现自定义注解的功能,包括定义注解、设置切点表达式以及使用@Around、@Before和@AfterReturning等注解进行方法拦截,特别是展示了如何通过自定义注解进行全局日志记录,以便追踪和分析方法的执行情况。
摘要由CSDN通过智能技术生成

一、导入依赖

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

二、定义自定义注解 

@Target(作用在类、字段或方法)

@Rentention(一般选Runntime)

@Retention(RetentionPolicy.RUNTIME)//定义注解的使用范围,编译时,还是运行时。。。
@Target(ElementType.METHOD)//定义注解用在哪里class,method。。。
public @interface Login {
    String value() default "";
}

三、注解贴在需要的地方

四、切点表达式 拿注解

作用域切点表达式切点表达式
作用在字段上get
作用在方法上@annotation 只能用于选择带有特定注解的方法作为连接点execution 则可以根据更多的方法特征进行匹配。比如参数、方法名
作用在类上within

@Around、@Before和@AfterReturning 是方法级别的三个注解。

其中@Around是在方法执行前后,如果方法执行失败了,可以捕捉异常,自己处理,或者抛出。如果抛出,则不再执行后续代码。

@Before在方法执行前

@AfterReturning 是在方法成功返回后(如果执行失败,抛异常,不执行这个切面方法)

以下以自定义注解,做全局日志记录为例 ,展示作用在方法上的注解,的@Around使用形式。

@Aspect
@Component
public class SystemLogAspect {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SystemLogAspect.class);

    @Around("@annotation(com.example.annotation.SystemLog)")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        SystemLog systemLog = method.getAnnotation(SystemLog.class);
        String message = systemLog.value();

        Long startTime = System.currentTimeMillis();
        Object result;
        try {
            result = joinPoint.proceed();
        } catch (Throwable throwable) {
            throw throwable;
        } finally {
            Long endTime = System.currentTimeMillis();
            long time = endTime - startTime;
            
            LOGGER.info("[SystemLog] {}.{}: {}ms", 
                joinPoint.getTarget().getClass().getName(), 
                method.getName(), time);
        }
        return result;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员大雨

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值