一、概述
除了使用AspectJ声明切面,Spring也支持通过Bean配置文件中声明切面。
基于注解声明切面,通过AspecJ注解,切面可以与AspectJ兼容,而基于XML文件的配置是Spring专有的,所以通常基于注解的方式要优于基于XML文件方式。
二、基于XML方声明切面
导入aop命名空间。
在Bean的配置文件中,配置切面的Bean,必须要有id属性,供<aop:aspect>
元素引用。
在Bean的配置文件中,所有Spring AOP的配置都必须定义在<aop:config>
元素内部。
在<aop:config>
元素内部,定义一个<aop:aspect>
元素来声明切面,用其ref属性指定切面的Bean。
举个例子:
<bean id ="loggingAspectXml" class ="com.sqp.spring.aop.xml.LoggingAspectXml" > </bean >
<aop:config >
<aop:aspect id ="loggingAspect" ref ="loggingAspectXml" > </aop:aspect >
</aop:config >
三、基于XML声明切入点
必须在<aop:config>
元素 或 <aop:aspect>
元素下,使用<aop:pointcut>
元素声明。 ① 如果声明在<aop:config>
下,对<aop:config>
下所有切面有效。 ② 如果声明在<aop:aspect>
下,只对当前切面有效。
基于XML声明的AOP,不允许在切入点表达式中,用名称引用其他表达式。
举个例子:
<aop:config >
<aop:pointcut id ="pointcutExpression"
expression ="execution(* com.sqp.spring.aop.dao.MyCalculator.*(int, int))" />
<aop:aspect id ="loggingAspect" ref ="loggingAspectXml" > </aop:aspect >
</aop:config >
四、基于XML声明切面的通知
通知声明在<aop:aspect>
元素下,每种通知对应一个XML元素。 ① 前置通知:<aop:before>
② 后置通知:<aop:after>
③ 返回通知:<aop:after-returning>
④ 异常通知:<aop:after-throwing>
⑤ 环绕通知:<aop:around>
method属性指定切面中的通知方法的名称,pointcut-ref 指向<aop:pointcut>
元素的id属性。
举个例子:
<aop:config >
<aop:pointcut id ="pointcutExpression"
expression ="execution(* com.sqp.spring.aop.dao.MyCalculator.*(..))" />
<aop:aspect id ="loggingAspect" ref ="loggingAspectXml" order ="1" >
<aop:before method ="beforeMethod" pointcut-ref ="pointcutExpression" />
<aop:after-returning method ="afterReturningMethod"
pointcut-ref ="pointcutExpression" returning ="result" />
<aop:after method ="afterMethod" pointcut-ref ="pointcutExpression" />
<aop:after-throwing method ="afterThrowingMethod"
pointcut-ref ="pointcutExpression" throwing ="ex" />
<aop:around method ="aroundMethod" pointcut-ref ="pointcutExpression" />
</aop:aspect >
</aop:config >