课时8:环绕通知

.1)环绕通知:在目标方法的前后丶异常发生时丶最终等各个地方都可以 进行通知 , 最强大的一个通知;

  可以获取目标方法的 全部控制权(目标方法是否执行丶执行之前丶执行之后丶参数丶返回值等)

  1.导入相应jar包 前置通知示例已经有了 这里就不做过多的讲解

  2.编写业务类以及编写环绕通知类

    2.1 业务类代码如下

package net.bdqn.hbz.aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * 环绕通知
 */
public class Surround  implements MethodInterceptor {

    /**
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object reult=null;
        try{
            System.out.println("执行了前置通知");
            //执行目标方法
            reult=invocation.proceed();
            //通过后置通知来获取一些信息
            System.out.println("后置通知:目标对象:"+invocation.getThis()+",目标方法:"+invocation.getMethod().getName()+",目标参数个数:"+
                    invocation.getArguments().length+",返回值:"+reult);
        }catch (Exception e){
            System.out.println("执行了环绕通知");
        }
        return reult;
    }
}

      2.1.1 目标方法的一些信息都可以通过MethodInvocation来获取

      2.1.2 如何控制方法是否执行目标方法 就是invocation.proceed(); 写了就执行 不写就不执行

   3.将切面和切入点进行一个连接

    3.1 注入这个异常通知类到SpringIOC容器当中

<!--    注入环绕通知类-->
    <bean id="surround" class="net.bdqn.hbz.aop.Surround"></bean>

    3.2 配置切面和切入点关联关系

    <!--   将addStudent  和  环绕通知进行关联-->
    <aop:config>
<!--        配置切入点信息-->
        <aop:pointcut id="addSurround" expression="execution(public void addStudent(net.bdqn.hbz.pojo.Student))"/>
<!--        配置连接-->
        <aop:advisor advice-ref="surround" pointcut-ref="addSurround"></aop:advisor>
    </aop:config>

  4.环绕通知的底层通过拦截器实现

原文地址:https://www.cnblogs.com/thisHBZ/p/12511716.html