Spring基于XML文件配置AOP

一、概述

  1. 除了使用AspectJ声明切面,Spring也支持通过Bean配置文件中声明切面。
  2. 基于注解声明切面,通过AspecJ注解,切面可以与AspectJ兼容,而基于XML文件的配置是Spring专有的,所以通常基于注解的方式要优于基于XML文件方式。

二、基于XML方声明切面

  1. 导入aop命名空间。
  2. 在Bean的配置文件中,配置切面的Bean,必须要有id属性,供<aop:aspect>元素引用。
  3. 在Bean的配置文件中,所有Spring AOP的配置都必须定义在<aop:config>元素内部。
  4. <aop:config>元素内部,定义一个<aop:aspect>元素来声明切面,用其ref属性指定切面的Bean。
  5. 举个例子:
<!-- 配置切面的Bean -->
<bean id="loggingAspectXml" class="com.sqp.spring.aop.xml.LoggingAspectXml"></bean>

<!-- 配置AOP -->
<aop:config>
    <aop:aspect id="loggingAspect" ref="loggingAspectXml"></aop:aspect>
</aop:config>

三、基于XML声明切入点

  1. 必须在<aop:config> 元素 或 <aop:aspect> 元素下,使用<aop:pointcut> 元素声明。
    ① 如果声明在<aop:config>下,对<aop:config> 下所有切面有效。
    ② 如果声明在<aop:aspect>下,只对当前切面有效。
  2. 基于XML声明的AOP,不允许在切入点表达式中,用名称引用其他表达式。
  3. 举个例子:
<!-- 配置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声明切面的通知

  1. 通知声明在<aop:aspect> 元素下,每种通知对应一个XML元素。
    ① 前置通知:<aop:before>
    ② 后置通知:<aop:after>
    ③ 返回通知:<aop:after-returning>
    ④ 异常通知:<aop:after-throwing>
    ⑤ 环绕通知:<aop:around>
  2. method属性指定切面中的通知方法的名称,pointcut-ref 指向<aop:pointcut> 元素的id属性。
  3. 举个例子:
<!-- 配置AOP -->
<aop:config>

    <!-- 配置切点表达式 -->
    <aop:pointcut id="pointcutExpression"
    expression="execution(* com.sqp.spring.aop.dao.MyCalculator.*(..))"/>

    <!-- 配置loggingAspect切面 -->
    <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>

猜你喜欢

转载自blog.csdn.net/qingpengshan/article/details/80593911
今日推荐