3.7 @Pointcut的配置
戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
[查看视频教程]
Pointcut表示切入点,我们在Hellowrold中使用的是内联式的切入点配置:
1 @Before("execution(* com.st.dk.demo7.service.BookService.saveBook(..))")
这种配置方式的缺点很明显,就是这个切入点是无法重复使用的,只能在当前的@Befor中使用。
其实我们可以申明一个切入点,方便重复使用。例如下面的程序:
1 /** 2 * @author 戴着假发的程序员 3 * 4 * @description 5 */ 6 @Component //将当前bean交给spring管理 7 @Aspect //定义为一个AspectBean 8 public class DkAspect { 9 @Pointcut("execution(* com.st.dk.demo7.service.BookService.saveBook(..))") 10 private void pointCut1(){} 11 //定义一个前置通知 12 @Before("pointCut1()") 13 private static void befor(){ 14 System.out.println("---前置通知---"); 15 } 16 //定义一个后置通知 17 @AfterReturning("pointCut1()") 18 public void afterReturning(){ 19 System.out.println("---后置通知---"); 20 } 21 }
上面的程序中我们使用@Pointcut修饰了方法poinCut1() ,@Pointcut中定义了切入点的位置。而pointCut1方法本身没有任何语句。这个方法的存在主要是方便后面对应这个切入点的引用。
我们在befor和afterReturning方法中通过 方法名 pointCut1()引用了上面的切入点。 这样我们的切入点就可以重复使用了。(关于后置通知和切入点的配置表达式请参考对应的章节)
测试:
1 @Test 2 public void testAopPointCut(){ 3 ApplicationContext ac = 4 new AnnotationConfigApplicationContext(Appconfig.class); 5 IBookService bean = ac.getBean(IBookService.class); 6 bean.saveBook("论一个假发程序员的修养"); 7 }
结果:

我是戴着假发的程序员,分享技术,分享经验,如果要转载,请注明:出自戴着假发的程序员

浙公网安备 33010602011771号