Spring AoP的切点匹配

Spring AoP的切点匹配主要使用切点表达式进行匹配,下面是两种常用情况。

1.基于方法匹配

设置表达式,execution()括号里面使用正则表达式匹配注解所在的方法。

复制代码
package com.example.springdemo.demos.a30;

import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zhou
 * @version 1.0
 * @description TODO
 * @date 2025/11/8 20:12
 */
public class a30 {
    public static void main(String[] args) throws NoSuchMethodException {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* bar())");
        System.out.println(pointcut.matches(T1.class.getMethod("foo"),T1.class));
        System.out.println(pointcut.matches(T1.class.getMethod("bar"),T1.class));
    }
    static class T1{
        @Transactional
        public void foo(){

        }
        public void bar(){

        }
    }
}

2.基于注解匹配

java 复制代码
AspectJExpressionPointcut pointcut1 = new AspectJExpressionPointcut();
        pointcut1.setExpression("@annotation(org.springframework.transaction.annotation.Transactional)");
        System.out.println(pointcut1.matches(T1.class.getMethod("foo"),T1.class));
        System.out.println(pointcut1.matches(T1.class.getMethod("bar"),T1.class));

表达式的值为@annotation+注解所在的类路径。

相关推荐
小成202303202654 小时前
Linux高级02
linux·开发语言
camellias_4 小时前
【无标题】
java·tomcat
知行合一。。。4 小时前
Python--04--数据容器(总结)
开发语言·python
咸鱼2.04 小时前
【java入门到放弃】需要背诵
java·开发语言
ZK_H4 小时前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
A.A呐4 小时前
【C++第二十九章】IO流
开发语言·c++
椰猫子4 小时前
Java:异常(exception)
java·开发语言
lifewange4 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
cmpxr_5 小时前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法
2401_827499995 小时前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python