java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springaop @annotation与execution

SpringAOP中@annotation与execution的深度示例对比分析

作者:bemyrunningdog

Spring AOP中@annotation通过注解标记方法,适合定制化横切逻辑;execution基于方法签名匹配,用于通用功能增强,两者互补,根据需求选择,本文给大家介绍SpringAOP中@annotation与execution的深度示例对比分析,感兴趣的朋友一起看看吧

在 Spring AOP 中,@annotationexecution 是两种常用的切点表达式(Pointcut Expression),用于定义哪些方法需要被切面(Aspect)拦截。它们的设计目的、匹配规则和适用场景有显著区别,以下从核心机制、语法、应用场景和示例进行对比分析:

🔍 ​一、核心概念与机制​

1. ​**@annotation表达式**​

2. ​**execution表达式**​

⚙️ ​二、语法详解​

1. ​**@annotation语法**​

@Before("@annotation(com.example.Loggable)")
public void logBefore(JoinPoint joinPoint) {
    // 通知逻辑
}

2. ​**execution语法**​

@Around("execution(* com.example.service.*.*(..))")
public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
    // 环绕通知逻辑
}

🧩 ​三、典型场景对比​

维度​**@annotation**​​**execution**​
匹配依据方法上的注解标记方法签名(包、类、方法名、参数等)
代码侵入性需在方法上添加注解无侵入,直接匹配方法结构
灵活性高(可通过注解参数定制逻辑)中(依赖方法命名和包结构)
适用案例- 权限校验(@RequireAuth
- 日志分级(@LogLevel("DEBUG")
- 接口耗时统计
- 全局事务管理
- 包级别异常处理
复杂匹配能力弱(仅依赖注解是否存在)强(支持通配符、逻辑运算符组合)

💻 ​四、代码示例​

1. ​**@annotation实现自定义日志**​

// 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {}
// 切面类
@Aspect
@Component
public class LogAspect {
    @Before("@annotation(com.example.Loggable)")
    public void logMethodCall(JoinPoint jp) {
        System.out.println("Log: " + jp.getSignature().getName());
    }
}
// 业务方法使用
@Service
public class UserService {
    @Loggable
    public void createUser() { ... }
}

2. ​**execution实现方法耗时统计**​

@Aspect
@Component
public class TimeAspect {
    @Around("execution(* com.example.service.*.*(..))")
    public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long duration = System.currentTimeMillis() - start;
        System.out.println(pjp.getSignature() + " executed in " + duration + "ms");
        return result;
    }
}

✅ ​五、如何选择?​​

@Before("@annotation(com.example.Auth) && execution(* com.service.*.*(..))")

💎 ​总结​

到此这篇关于SpringAOP中@annotation与execution的深度对比的文章就介绍到这了,更多相关springaop @annotation与execution内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文