5.5 Spring的通知(Advice)

5.5  Spring的通知(Advice)

Spring提供了5种Advice类型:Interception Around、Before、After Returning、Throw和Introduction。它们分别在以下情况下被调用:在JointPoint前后、JointPoint前、JointPoint后、JointPoint抛出异常时、JointPoint调用完毕后。下面来进行更详细的讲解。

5.5.1  Interception Around通知

Interception Around通知会在JointPoint的前后执行,前面示例中的LogProxy就是一个Interception Around通知,它在考勤审核程序的前后都执行了。Spring中最基本的通知类型便是Interception Around通知。实现Interception Around通知的类需要实现接口MethodInterceptor,示例代码如下:

public class LogInterceptor implements MethodInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {

        System.out.println(" 开始审核数据...");

        Object rval = invocation.proceed();

        System.out.println(" 审核数据结束…");

        return rval;

    }

}

5.5.2  Before通知

Before通知只在JointPoint前执行,实现Before通知的类需要实现接口MethodBeforeAdvice,示例代码如下:

扫描二维码关注公众号,回复: 481346 查看本文章

public class LogBeforeAdvice implements MethodBeforeAdvice {

    public void before(Method m, Object[] args, Object target) throws Throwable {

        System.out.println(" 开始审核数据...");

    }

}

5.5.3  After Returning通知

After Returning通知只在JointPoint后执行,实现After Returning通知的类需要实现接口AfterReturningAdvice,示例代码如下:

public class LogAfterAdvice implements AfterReturningAdvice {

    public void afterReturning (Method m, Object[] args, Object target) throws Throwable {

        System.out.println(" 审核数据结束...");

    }

}

5.5.4  Throw通知

Throw通知只在JointPoint抛出异常时执行,实现Throw通知的类需要实现接口ThrowsAdvice,示例代码如下:

public class LogThrowAdvice implements ThrowsAdvice {

    public void afterThrowing (RemoteException ex) throws Throwable {

        System.out.println(" 审核数据抛出异常,请检查..." + ex);

    }

}

5.5.5  Introduction通知

Introduction通知只在JointPoint调用完毕后执行,实现Introduction通知的类需要实现接口IntroductionAdvisor和接口IntroductionInterceptor。

前面所讲的知识点,更多的是理论,下面的章节将会讲述更多的实例,来帮助读者更好地理解上面的理论知识。

 

5.6  Spring的Advisor

前面讲过,Advisor是Pointcut和Advice的配置器,它是将Advice注入程序中Pointcut位置的代码。org.springframework.aop.support.DefaultPointcutAdvisor是最通用的Advisor类。在Spring中,主要通过XML的方式来配置Pointcut和Advice。

猜你喜欢

转载自xiaowei2002.iteye.com/blog/2174288
5.5
今日推荐