3.16 @Pointcut的表达式-@annotation
戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
[查看视频教程]
限制连接点的匹配,其中连接点的主题(在 Spring AOP 中执行的方法)具有给定的 annotation。
官方案例:
任何连接点(仅在 Spring AOP 中执行方法),其中执行方法具有@Transactional
annotation:
@annotation(org.springframework.transaction.annotation.Transactional)
官方的案例已经说的很清楚了,就是@annotation是匹配拥有指定注解的方法的。这里要注意,@annotation只匹配实现类中的有注解的方法,不会匹配接口中的注解方法。
看案例:
我们准备接口:
1 /** 2 * @author 戴着假发的程序员 3 * 4 * @description 5 */ 6 public interface IBookService { 7 //@DkAnnotation// 这里的注解是不会被匹配的 8 public void saveBook(String title); 9 }
实现类:
1 /** 2 * @author 戴着假发的程序员 3 * 4 * @description 5 */ 6 @Component 7 public class BookService implements IBookService{ 8 @Override 9 @DkAnnotation //这里的注解会被匹配 10 public void saveBook(String title){ 11 System.out.println("保存图书:"+title); 12 } 13 public void saveBook(String title,int count){ 14 System.out.println("保存"+title+","+count+"次"); 15 } 16 }
修改Aspect类:
1 /** 2 * @author 戴着假发的程序员 3 * 4 * @description 5 */ 6 @Component //将当前bean交给spring管理 7 @Aspect //定义为一个AspectBean 8 public class DkAspect { 9 //使用@annotation配置匹配所有还有指定注解的方法 10 @Pointcut("@annotation(com.st.dk.demo7.annotations.DkAnnotation)") 11 private void pointCut1(){} 12 //定义一个前置通知 13 @Before("pointCut1()") 14 private static void befor(){ 15 System.out.println("---前置通知---"); 16 } 17 }
测试:
1 @Test 2 public void testAopPoint_annotation(){ 3 ApplicationContext ac = 4 new AnnotationConfigApplicationContext(Appconfig.class); 5 IBookService bean = ac.getBean(IBookService.class); 6 bean.saveBook("程序员的修养"); 7 }
结果:
我是戴着假发的程序员,分享技术,分享经验,如果要转载,请注明:出自戴着假发的程序员
分类:
spring操作手册
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律