第3章 Spring的AOP实现
3.1 正则表达式简介
3.2 认识AOP
3.2.1 代理机制
3.2.2 AOP中的常用术语
3.3 传统的AOP支持
3.3.1 前置通知Before Advice
3.3.2 后置通知 After Advice
3.3.3 环绕通知 Around Advice
3.3.4 异常通知 Throw Advice
3.3.5 NameMatchMethodPointAdvisor
3.3.6 RegexpMethodPointcutAdvisor
3.3.7 DefaultPointcutAdvisor
3.3.8 引介
3.4 Spring 2.0中的AOP
3.4.1 Spring2.0中的Pointcut定义
3.4.2 基于XML Schema的前置通知
3.4.3 基于Annotation的前置通知
3.4.4 基于XML Schema的后置通知
3.4.5 基于Annotation的后置通知
3.4.6 基于XML Schema的环绕通知
3.4.7 基于Annotation的环绕通知
3.4.8 基于XML Schema的异常通知
3.4.9 基于Annotation的异常通知
3.4.10 SpringAOP综合运用之超级玛丽完结篇
3.5 小结
试读部分:
3.4 Spring 2.0中的AOP
Spring2.0中除了支持3.3节中讲述的传统的AOP支持,还提供了2种实现AOP的方式:
1、基于XML的配置,使用基于Schema的XML配置来完成AOP,而且Advice也不用再实现任何其他特定的接口。
2、使用JDK5的注释来完成AOP的实现,只需要一个简单的标签就完成了AOP的整个过程。
3.4.1 Spring2.0中的Pointcut定义
Spring2.0中的切入点Pointcut的定义有2种方式,表达式配置和Annotation配置,下面具体讲解。
1、表达式
Spring2.0中的Pointcut的定义支持的关键字有:execution(方法执行的连接点,
这是 Spring 中最主要的切入点指定者),within(限定匹配特定类型的连接点),this(连接点本身),target(连接点目标对象),arg(连接点参数)等,表达式的定义如下格式:
execution(modifiers-pattern?
ret-type-pattern
declaring-type-pattern?
name-pattern(param-pattern)
throws-pattern?)
有“?”号的部分表示可省略的,modifers-pattern 表示修饰符如 public、protected 等,
ret-type-pattern 表示方法返回类型,declaring-type-pattern 代表特定的类,name-pattern 代表方法名称,param-pattern表示参数,throws-pattern表示抛出的异常。在切入点表达式中,可以使用*来代表任意字符,用..来表示任意个参数(注意这里不是正则表达式),比喻前面的
execution(void spring.chapter3.proxy.Component.business*(..))
就表示执行spring.chapter3.proxy.Component中所有business开头的方法,这里的省略了第一个参数,第二个参数为void,在很多情况下传回值可以用*表示所有传回值均匹配,第三个参数这里指定了类spring.chapter3.proxy.Component,第四个参数为business*表示所有business开头的方法,这里方法的参数为(..),表示0个或者任意个参数,也可以使用*来指定任意参数,比如business*(*,String),表示2个参数,第一个为任意类型,第二个为String类型,同时还可以使用within关键字来表示,例如within(spring.chapter3.proxy.*)表示spring.chapter3.proxy包下的任何方法,由于within用的比较少,同时功能也有所局限,这里不再花太多的篇幅介绍。
2、Annotation表达式
基于JDK5.0以上我们还可以使用Annotation来配置切入点,表达式写法和前面一样,只不过这里不再需要使用配置文件来声明表达式了,直接使用@Pointcut("execution()")就可以表示一个切入点了,以后在需要应用该切入点的时候就可以使用其标识的方法了。
比如:
@Pointcut("execution(void spring.chapter3.proxy.Component.business*(..))")
public void beforePointcut(){}
表示在spring.chapter3.proxy.Component中所有business开头的方法这样一个切入点,在执行前置通知或者其他需要使用的时候直接使用:
@before("beforePointcut")
也就相当于@before("execution(void spring.chapter3.proxy.Component.business*(..))")
3.4.2基于XML Schema的前置通知
Spring2.0提供了Schema来通过配置文件解决了前置通知的限定接口,以改写3.3.1中的实例来讲解,AdviceBeforeComponent不再需要实现MethodBeforeAdvice接口,改后的代码如下:
发表于 @ 2008年01月17日 15:11:00|评论(loading...)|编辑