(3).最终通知AfterAdvice:
a.最终通知AfterAdvice的源码:
[java] view plaincopy- public interface AfterAdvice extends Advice { }
和前置通知一样,最终通知也是继承了AOP联盟定义的Advice接口。
b.最终通知的子接口后置通知AfterReturningAdvice:
最终通知的继承体系中,后置通知AfterReturningAdvice接口继承了最终通知接口,源码如下:
[java] view plaincopy- public interface AfterReturningAdvice extends AfterAdvice { //后置通知的回调方法,在目标方法对象调用结束并成功返回之后调用
- // returnValue参数为目标方法对象的返回值,method参数为目标方法对象,args为 //目标方法对象的输入参数
- void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable; }
c.后置通知的实现类CountingAfterReturningAdvice:
后置通知接口AfterReturningAdvice的实现类也比较多,我们以CountingAfterReturningAdvice类为例,分析后置通知的具体操作:
[java] view plaincopy- public class CountingAfterReturningAdvice extends MethodCounter implements AfterReturningAdvice { //实现后置通知AfterReturningAdvice的回调方法
- public void afterReturning(Object o, Method m, Object[] args, Object target) throws Throwable { //调用父类MethodCounter的count方法,统计方法的调用次数
- count(m); }
- }
(4).例外通知ThrowAdvice:
a.例外通知ThrowAdvice的源码
例外通知ThrowAdvice接口也继承自最终通知AfterAdvice,其源码如下:
[java] view plaincopy- public interface ThrowsAdvice extends AfterAdvice { }
b.例外通知实现类CountingThrowsAdvice:
例外通知并没有指定需要实现的接口方法,它在抛出异常时被回调,这个回调是AOP利用JDK的反射机制来完成的,我们以其实现类CountingThrowsAdvice为例分析例外通知的用法,源码如下:
[java] view plaincopy- public static class CountingThrowsAdvice extends MethodCounter implements ThrowsAdvice { //当抛出IO类型的异常时的回调方法,统计异常被调用的次数
- public void afterThrowing(IOException ex) throws Throwable { count(IOException.class.getName());
- } //当抛出UncheckedException类型异常时的回调方法,统计异常被调用的次数
- public void afterThrowing(UncheckedException ex) throws Throwable { count(UncheckedException.class.getName());
- } }
7.Pointcur切入点:
Pointcut切入点决定通知Advice应该作用于哪个连接点,即通过Pointcut切入点来定义目标对象中需要使用AOP增强的方法集合,这些集合的选取可以按照一定的规则来完成。
Pointcut通常意味着标识方法,这些需要增强的方法可以被某个正则表达式进行标识,或者根据指定方法名进行匹配等。
(1).Pointcut切入点源码:
[java] view plaincopy- public interface Pointcut { //获取类过滤器
- ClassFilter getClassFilter(); //获取匹配切入点的方法
- MethodMatcher getMethodMatcher(); //总匹配的标准切入点实例
- Pointcut TRUE = TruePointcut.INSTANCE; }
(2).Pointcut接口的实现类JdkRegexpMethodPointcut:
查看Pointcut切入点的继承体系,发现Pointcut切入点的实现类非常的多,如针对注解配置的AnnotationMatchingPointcut、针对正则表达式的JdkRegexpMethodPointcut等等,我们以JdkRegexpMethodPointcut为例,分析切入点匹配的具体实现,源码如下:
[java] view plaincopy- public class JdkRegexpMethodPointcut extends AbstractRegexpMethodPointcut { //要编译的正则表达式模式
- private Pattern[] compiledPatterns = new Pattern[0]; //编译时要排除的正则表达式模式
- private Pattern[] compiledExclusionPatterns = new Pattern[0]; //将给定的模式字符串数组初始化为编译的正则表达式模式
- protected void initPatternRepresentation(String[] patterns) throws PatternSynt
- public interface ThrowsAdvice extends AfterAdvice { }