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     }

结果:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM