3.20 切面发布-前置通知

戴着假发的程序员出品  抖音ID:戴着假发的程序员  欢迎关注

[查看视频教程]

前置通知的意思是在目标方法执行之前执行增强程序。前面的例子我们也写过潜质通知。

注意,前置通知仅仅就是前置增强,前置通知并不能改变目标方法的执行。更不能阻止目标方法的执行。

现在我们来仔细分析以下前置通知的案例:

我们准备一个业务类InfoService,其中有一个方法为showInfo(String info).

/**
 * @author 戴着假发的程序员
 * 
 * @description
 */
@Component
public class InfoService {
    public void showInfo(String info){
        System.out.println("InfoService-showInfo输出信息:"+info);
    }
}

  添加一个Aspect类,在其中添加一个前置通知:

 1 /**
 2  * @author 戴着假发的程序员
 3  * 
 4  * @description
 5  */
 6 @Component //将当前bean交给spring管理
 7 @Aspect //定义为一个AspectBean
 8 public class DkAspect {
 9 
10     @Pointcut("execution(* com.st.service..*.*(..))")
11     public void pointcut1(){}
12 
13     @Before("pointcut1()")
14     public void before(){
15         System.out.println("--这里是前置通知--");
16     }
17 }

主配置类:

 1 /**
 2  * @author 戴着假发的程序员
 3  * 
 4  * @description
 5  */
 6 @Configuration
 7 @ComponentScan("com.st")
 8 @EnableAspectJAutoProxy
 9 public class Appconfig {
10 }

测试:

1 @Test
2 public void testBefore(){
3     ApplicationContext ac =
4             new AnnotationConfigApplicationContext(AppConfig.class);
5     InfoService bean = ac.getBean(InfoService.class);
6     bean.showInfo("今天天气不错");
7 }

结果:

这里前置通知已经生效。

接下来我们来看看前置通知的方法中可以传递的参数。

首先就是可以传递一个JoinPoint类,这个类在前面已经解释过,除此之外,我们还可以传递我们拦截的方法的参数。

看下面案例:

我们修改Aspect类

 1 /**
 2  * @author 戴着假发的程序员
 3  * 
 4  * @description
 5  */
 6 @Component
 7 @Aspect
 8 public class DkAspect {
 9     @Pointcut("execution(* com.st.dk.demo8.service..*.*(..))")
10     public void pointcut1(){}
11 
12     /**
13      * 这里注意
14      * 我们可以传入JoinPoint不用解释
15      * 如果我们希望传入其他参数,则需要使用args指定,
16      * 这里的args(info)中的info必须和参数info一致。
17      * 而且要和被拦截的方法中的参数名也一致。
18      */
19     @Before("pointcut1() && args(info)")
20     public void before(JoinPoint joinPoint,String info){
21         System.out.println("--这里是前置通知开始--");
22         System.out.println("目标对象:"+joinPoint.getTarget());
23         System.out.println("代理对象:"+joinPoint.getThis());
24         System.out.println("增强的方法的参数列表:"+ Arrays.toString(joinPoint.getArgs()));
25         System.out.println("我们手动传入的参数info:"+info);
26         System.out.println("--这里是前置通知结束s--");
27     }
28 }

再测试:

这里我们再次提醒一个配置,我们可以通过JoinPoint获取被拦截方法的参数列表数组,但是如果我们希望某个指定的参数直接传递到我们的增强方法中时,我们需要使用args(参数名)匹配有指定参数的方法,所有的相关参数名必须相同。

如果还不明白请参看视频讲解。

posted @ 2020-10-28 17:22  戴着假发的程序员0-1  阅读(168)  评论(0编辑  收藏  举报