戴着假發的程序員出品 抖音ID:戴着假發的程序員 歡迎關注
[查看視頻教程]
限制與連接點的匹配(使用 Spring AOP 時執行方法),其中執行 object 的 class 具有給定類型的 annotation。
我的解釋就是:@target會匹配所有擁有@target指定注解類型的目標類。 注意是目標類,注解在接口和方法上面是無效的。
如果還不明白就看我的案例。
官方案例:
目標 object 具有@Transactional
annotation 的任何連接點(僅在 Spring AOP 中執行方法):
@target(org.springframework.transaction.annotation.Transactional)
我們的案例:
我們自定義一個注解:
1 @Retention(RetentionPolicy.RUNTIME) 2 public @interface DkAnnotation { 3 }
在我們的BookService實現類上添加注解,注意是添加在實現類上,並不是接口和方法上。
1 /** 2 * @author 戴着假發的程序員 3 * 4 * @description 5 */ 6 @Component 7 @DkAnnotation //我自己定義的注解,當然也可以使用其他注解 8 public class BookService{ 9 @Override 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類中添加pointcut配置:
1 /** 2 * @author 戴着假發的程序員 3 * 4 * @description 5 */ 6 @Component //將當前bean交給spring管理 7 @Aspect //定義為一個AspectBean 8 public class DkAspect { 9 //使用@Target配置有DkAnnotation注解的目標類 10 @Pointcut("@target(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_Target(){ 3 ApplicationContext ac = 4 new AnnotationConfigApplicationContext(Appconfig.class); 5 BookService bean = ac.getBean(BookService.class); 6 bean.saveBook("論一個假發程序員的修養"); 7 bean.saveBook("java從入門到頸椎康復之路",10); 8 }
結果:
我們會發現我們的方法全部被增強了。
再次提醒:@target只是對目標類的注解生效,對接口和方法的注解是不生效的。對其子類也不生效。
我們讓BooService實現接口IBookService,然后再IBookServie接口上添加注解@DkAnnotation,或者在某個方法上添加注解@DkAnnotion,都不會被匹配。如果只在父類上添加了注解,子類不添加注解,則子類的任何方法也不會被匹配。 這個我們這里就暫時不測試,你可以自己測試以下。
如果還沒明白,建議查看視頻講解。