// 引入必要的包
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
// 定义一个切面类
@Aspect
@Component
public class LoggingAspect {
// 定义切入点,匹配所有以 "execute" 开头的方法
@Pointcut("execution(* com.example.service..*execute*(..))")
public void executeMethods() {}
// 在方法执行前进行日志记录
@Before("executeMethods()")
public void logBefore() {
System.out.println("LoggingAspect: Before method execution.");
}
// 在方法成功返回后进行日志记录
@AfterReturning(pointcut = "executeMethods()", returning = "result")
public void logAfterReturning(Object result) {
System.out.println("LoggingAspect: Method returned with result: " + result);
}
// 在方法抛出异常时进行日志记录
@AfterThrowing(pointcut = "executeMethods()", throwing = "ex")
public void logAfterThrowing(Exception ex) {
System.out.println("LoggingAspect: Exception thrown: " + ex.getMessage());
}
}
@Aspect 注解标记类为切面类,并用 @Component 注解使其成为 Spring 容器中的一个 Bean。@Pointcut 注解定义一个切入点表达式,匹配特定的方法签名。这里匹配的是 com.example.service 包下所有以 execute 开头的方法。@Before 注解定义在方法执行前的日志记录逻辑。@AfterReturning 注解定义在方法成功返回后的日志记录逻辑,并获取返回值。@AfterThrowing 注解定义在方法抛出异常时的日志记录逻辑,并获取异常对象。这个例子展示了如何使用 Spring AOP 来实现方法调用的日志记录功能。
上一篇:java压缩图片
下一篇:java charat
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站