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