首页 > 其他 > 详细

第六章、以XML方式配置切面

时间:2020-09-16 12:44:21      阅读:79      评论:0      收藏:0      [点我收藏+]

除了使用AspectJ注解声明切面,Spring也支持在bean配置文件中声明切面。这种声明是通过aop名称空间中的XML元素完成的。 ? 正常情况下,基于注解的声明要优先于基于XML的声明。通过AspectJ注解,切面可以与AspectJ兼容,而基于XML的配置则是Spring专有的。由于AspectJ得到越来越多的 AOP框架支持,所以以注解风格编写的切面将会有更多重用的机会。

一、配置细节

在bean配置文件中,所有的Spring AOP配置都必须定义在<aop:config>元素内部。对于每个切面而言,都要创建一个<aop:aspect>元素来为具体的切面实现引用后端bean实例。 ?

切面bean必须有一个标识符,供<aop:aspect>元素引用。

<bean id="calculatorLoggingAspect" class="com.jdy.spring2020.aop.CalculatorLoggingAspect"/>
   <aop:config>
      <aop:aspect id="calculatorLoggingAspect" order="0" ref="calculatorLoggingAspect">
       </aop:aspect>
   </aop:config> 

 

二、声明切入点

  1. 切入点使用<aop:pointcut>元素声明。

  2. 切入点必须定义在<aop:aspect>元素下,或者直接定义在<aop:config>元素下。

    • 定义在<aop:aspect>元素下:只对当前切面有效

    • 定义在<aop:config>元素下:对所有切面都有效

  3. 基于XML的AOP配置不允许在切入点表达式中用名称引用其他切入点。

<bean id="calculatorLoggingAspect" class="com.jdy.spring2020.aop.CalculatorLoggingAspect"/>
    <aop:config>
      <aop:pointcut id="pointcut01" expression="execution( com.jdy.spring2020.scan.service.impl.ArithmeticCalculatorImpl.add(int,int))"/>
      <aop:aspect id="calculatorLoggingAspect" order="0" ref="calculatorLoggingAspect">
    </aop:aspect>
</aop:config>

 

三、声明通知

  1. 在aop名称空间中,每种通知类型都对应一个特定的XML元素。

  2. 通知元素需要使用<pointcut-ref>来引用切入点,或用<pointcut>直接嵌入切入点表达式。

  3. method属性指定切面类中通知方法的名称

<bean id="calculatorLoggingAspect" class="com.jdy.spring2020.aop.CalculatorLoggingAspect"/>
  <aop:config>
      <aop:pointcut id="pointcut01" expression="execution( com.jdy.spring2020.scan.service.impl.ArithmeticCalculatorImpl.add(int,int))"/>
      <aop:aspect id="calculatorLoggingAspect" order="0" ref="calculatorLoggingAspect">
          <aop:after method="after" pointcut-ref="pointcut01">
        </
aop:after> </aop:aspect> </aop:config>

 

第六章、以XML方式配置切面

原文:https://www.cnblogs.com/jdy1022/p/13678278.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!