戴着假發的程序員出品 抖音ID:戴着假發的程序員 歡迎關注
[查看視頻教程]
限制匹配到具有給定 annotation 的類型中的連接點(使用 Spring AOP 時執行在具有給定 annotation 的類型中聲明的方法)。
官方給出的案例:
任何連接點(僅在 Spring AOP 中執行方法),其中目標 object 的聲明類型具有@Transactional
annotation:
@within(org.springframework.transaction.annotation.Transactional)
關於@within注解我們這里只做一個說明,因為@within和@target只有一點不同,其他都一樣。
我們知道@target只對指定的當前類生效,也就是說指定的注解配置在當前類上才生效,其他的情況:配置再其接口,方法都不生效,並且子類中的任何方法也不會生效。
@within和@target的區別在於@within會對子類繼承的方法生效,但是子類的其他方法或者子類重寫了父類的方法就不會在生效。
看看這樣的例子:
我們BooService類,BookService上有指定的注解,有兩個方法。
1 /** 2 * @author 戴着假發的程序員 3 * 4 * @description 5 */ 6 @Component 7 @DkAnnotation 8 public class BookService{ 9 public void saveBook(String title){ 10 System.out.println("保存圖書:"+title); 11 } 12 public void saveBook(String title,int count){ 13 System.out.println("保存"+title+","+count+"次"); 14 } 15 }
添加一個子類SubBookService,重寫父類的其中一個方法,並且添加一個自己的方法:
注意子類不添加指定的注解
1 /** 2 * @author 戴着假發的程序員 3 * 4 * @description 5 */ 6 @Component 7 public class SubBookService extends BookService { 8 @Override 9 public void saveBook(String title){ 10 System.out.println("子類重寫的方法-saveBook-保存圖書:"+title); 11 } 12 public void subSaveBook(String title){ 13 System.out.println("子類自己的方法-subSaveBook-保存圖書:"+title); 14 } 15 }
修改Aspect類,修改配置:
1 /** 2 * @author 戴着假發的程序員 3 * 4 * @description 5 */ 6 @Component //將當前bean交給spring管理 7 @Aspect //定義為一個AspectBean 8 public class DkAspect { 9 //使用@within配置匹配所有還有指定注解的方法 10 @Pointcut("@within(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_within(){ 3 ApplicationContext ac = 4 new AnnotationConfigApplicationContext(Appconfig.class); 5 SubBookService bean = ac.getBean(SubBookService.class); 6 bean.saveBook("程序員的修養"); 7 bean.saveBook("假發的穿戴技巧",10); 8 bean.subSaveBook("頸椎康復之路"); 9 }
我們會發現只有繼承自父類的方法被匹配增強了,其他的重寫和自己定義的方法都沒有匹配。