Advice(通知)是面向切面编程中的一个很是重要的概念。咱们都知道,AOP的目的在于对目标类或目标方法的逻辑加强(如:日志逻辑、统计逻辑、访问控制逻辑等),那么Advice就表明要加强的具体逻辑。Advice接口由AOP联盟(aopalliance.org)定义,它只是一个标记接口,用来强调概念,没有定义任何功能(或者说没有定义加强方式或加强内容)。java
Advice体系图以下:spring
AOP联盟在Advice的基础上扩展定义了子接口——Interceptor(拦截器)。拦截器定义了通知的加强方式,也就是经过对Joinpoint(链接点)的拦截。AOP联盟的原话是这样的:编程
A generic interceptor can intercept runtime events that occur within a base program. Those events are materialized by (reified in) joinpoints. Runtime joinpoints can be invocations, field access, exceptions...框架
如下是个人翻译:函数
一个通用的拦截器能够拦截发生在基础程序中的运行时事件。这些事件被链接点具体化。运行时链接点能够是一次方法调用、字段访问、异常产生等等。翻译
很明显,Interceptor接口也在强调概念而非功能,也是一个标记接口。 由Interceptor扩展出的ConstructorInterceptor和MethodInterceptor两个子接口,才具体定义了拦截方式。它们一个用于拦截构造方法,一个用于拦截普通方法。代码以下:日志
public interface ConstructorInterceptor extends Interceptor { Object construct(ConstructorInvocation invocation) throws Throwable; } public interface MethodInterceptor extends Interceptor { Object invoke(MethodInvocation invocation) throws Throwable; }
可是,spring框架并无支持AOP联盟对构造方法的拦截,缘由很简单,spring框架自己,经过BeanPostProcessor的定义,对bean的生命周期扩展已经很充分了。code
MethodInterceptor只定义了加强方式,咱们能够经过实现此接口,自定义具体的加强内容。固然,spring框架也提供了3种预约义的加强内容——BeforeAdvice(前置通知)、AfterAdvice(后置通知)和DynamicIntroductionAdvice(动态引介通知)。BeforeAdvice和AfterAdvice更确切地说是定义了加强内容的执行时机(方法调用以前仍是以后);而DynamicIntroductionAdvice比较特殊,它能够编辑目标类要实现的接口列表。最后,spring预约义的通知仍是要经过对应的适配器,适配成MethodInterceptor接口类型的对象(如:MethodBeforeAdviceInterceptor负责适配MethodBeforeAdvice)。对象
既然MethodInterceptor是核心,那么下面重点介绍如下MethodInterceptor的体系,以下图:接口
重点介绍几个经常使用拦截器(其余的读者可自行研究):