强大的【环绕通知】

AOP (面向切面编程) :在程序运行时,动态的将代码块切入到某个类的某个方法的某个位置(前面、后面、发生异常时)上。

前置通知:在某个方法之前执行   实现MethodBeforeAdvice接口

后置通知:在某个方法之后执行   实现AfterReturningAdvice接口

异常通知:在某个方法发生异常时执行    实现ThrowsAdvice接口

环绕通知:可以在方法之前、之后、发生异常时执行!   实现MethodInterceptor接口

最终通知:不论目标方法是否发生异常都会执行

 

切点和切面:切点是:在目标方法之前这个点、目标方法之后这个点、在目标方法发生异常这个点

      切面是:在切点执行的代码块。

环绕通知:

  可以获取目标方法的 完全控制权!(方法是否执行、控制参数、控制返回值)

  在使用环绕通知时,目标方法的一切信息,都可以通过invocation(invoke方法传进去的参数名称)参数获取到

public class SurroundMethod implements MethodInterceptor{

    public Object invoke(MethodInvocation invocation) {
        Object result = null;
        try {
            System.out.println("环绕通知里面的【前置通知】。。。");
            result = invocation.proceed();  //这里相当于执行目标方法 如果不写目标方法就不会执行
            // result是目标方法的返回值
            System.out.println("环绕通知里面的【后置通知】...");
        } catch (Throwable e) {
            System.out.println("这里是执行环绕通知里面的【异常通知】。。。");
            e.printStackTrace();
        } finally{
              System.out.println("这里是执行环绕通知里面的【最终通知】");
          }
        return result;
        //也可以返回其他  return “123”;  那么目标方法的返回值就是 "123"
    }
    
}

 

在applicationContext.xml文件中的配置  然后执行目标方法

<bean></bean>  通知类要写进来

<aop:config>
<!-- 切点 -->
<aop:pointcut expression="execution(【这里是目标方法的具体信息】public * com.service.AddStudent.addStudent())" id="addStudent1"/>
<!-- 连线 切点和切面连接起来 -->
<aop:advisor advice-ref="interceptMethod" pointcut-ref="addStudent1"/>
</aop:config>

 

posted @ 2019-04-08 21:38  DDiamondd  阅读(2878)  评论(0编辑  收藏  举报
TOP