springboot写一个添加aop日志的自定义注解实例(入门)

发布时间:2023年12月18日

以下是一个使用Spring Boot编写的自定义注解示例,用于添加AOP日志功能:

创建一个自定义注解 Loggable,用于标记需要添加AOP日志的方法。
java Copy code
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Loggable {
}
创建一个切面类 LoggingAspect,用于在被 Loggable 注解标记的方法执行前后添加日志记录。
java Copy code
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.AfterReturning;
import org.springframework.stereotype.Component;

import java.util.logging.Logger;

@Aspect
@Component
public class LoggingAspect {

? ? private Logger logger = Logger.getLogger(LoggingAspect.class.getName());

? ? @Before("@annotation(com.example.Loggable)")
? ? public void logMethodExecution(JoinPoint joinPoint) {
? ? ? ? String methodName = joinPoint.getSignature().getName();
? ? ? ? logger.info("Executing method: " + methodName);
? ? }

? ? @AfterReturning(pointcut = "@annotation(com.example.Loggable)", returning = "result")
? ? public void logMethodReturnValue(JoinPoint joinPoint, Object result) {
? ? ? ? String methodName = joinPoint.getSignature().getName();
? ? ? ? logger.info("Method " + methodName + " returned: " + result);
? ? }
}
在需要添加日志的方法上添加 @Loggable 注解。
java Copy code
@Service
public class ExampleService {

? ? @Loggable
? ? public void doSomething() {
? ? ? ? // Method implementation
? ? }

? ? @Loggable
? ? public String calculateResult(int a, int b) {
? ? ? ? // Method implementation
? ? ? ? return "Result";
? ? }
}
在上述示例中,我们创建了一个切面类 LoggingAspect,通过 @Before 和 @AfterReturning 注解来定义在被 Loggable 注解标记的方法执行前后要执行的逻辑。切面类会记录方法的名称,并使用Java日志进行输出。

在 ExampleService 类中,我们在 doSomething 和 calculateResult 方法上添加了 @Loggable 注解,这样就会触发切面类中定义的日志记录逻辑。

当调用被 @Loggable 注解标记的方法时,将会在控制台输出相关的日志信息,包括方法的名称和返回值(在返回类型不为 void 的情况下)。

你可以根据实际需求扩展该示例,并在切面类中添加自己所需要的日志记录逻辑。

注解 @Before("@annotation(com.example.Loggable)") 是切面类中的一个方法级别的切点表达式,它被用于定义在被 Loggable 注解标记的方法执行前执行的逻辑。

具体解释如下:

@Before: 这是一个 AspectJ 切面注解,表示该方法将在目标方法执行之前执行。
"@annotation(com.example.Loggable)": 这是切点表达式,指定了要拦截的目标方法。其中,@annotation() 用于匹配带有特定注解的方法,而 com.example.Loggable 是我们自定义的注解类。
因此,当使用 @Before("@annotation(com.example.Loggable)") 注解一个方法时,这个方法就会在所有被 Loggable 注解标记的方法执行之前执行。在该方法内部,你可以编写相应的代码,实现自定义的日志记录逻辑或其他操作。

总结起来,@Before("@annotation(com.example.Loggable)") 注解告诉AOP框架,在被 Loggable 注解标记的方法执行前,执行当前方法的逻辑。

文章来源:https://blog.csdn.net/gb4215287/article/details/135024207
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。