目标bean
package com.example.service;
import org.springframework.stereotype.Component;
@Component
public class UserService {
public String sayHello() {
return "Hello!";
}
}
示例1
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecution {
}
@Aspect
@Order(100)
public class AnnotationAspect {
@Before("@annotation(LogExecution)")
public void logBeforeAnnotatedMethod() {
System.out.println("Executing annotated method...");
}
}
示例2
@Aspect
@Order(10)
public class LoggingAspect {
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() {
}
@Before("serviceMethods()")
public void logBefore(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] methodArgs = joinPoint.getArgs();
System.out.println("前置通知:方法 " + methodName + " 开始执行");
}
@After("serviceMethods()")
public void logAfter(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("前置通知:方法 " + methodName + " 执行结束");
}
@AfterReturning(pointcut = "serviceMethods()", returning = "result")
public void logAfterReturning(Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("返回通知:方法 " + methodName + " 正常执行完毕,结果为:" + result);
}
@AfterThrowing(pointcut = "serviceMethods()", throwing = "ex")
public void logAfterThrowing(Throwable ex) {
System.out.println("异常通知:方法 " + methodName + " 发生异常,异常为:" + ex);
}
}
示例3
@Around("serviceMethods()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Before...");
Object result = null;
try {
result = joinPoint.proceed();
System.out.println("AfterReturning");
} catch (Exception e) {
System.out.println("AfterThrowing...");
throw e;
} finally {
System.out.println("After...");
}
return result;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具