Spring学习笔记4

xiaoxiao2021-02-28  14

04 XML 方式配置切面   1.概述 除了使用AspectJ 注解声明切面,Spring 也支持在bean 配置文件中声明切面。这种声明是通过aop 名称空间中的XML 元素完成的。 正常情况下,基于注解的声明要优先于基于XML 的声明。通过AspectJ 注解,切面可以与AspectJ 兼容,而基于XML 的配置则是Spring 专有的。由于AspectJ 得到越来越多的 AOP 框架支持,所以以注解风格编写的切面将会有更多重用的机会。 2.配置细节 bean 配置文件中,所有的Spring AOP 配置都必须定义在<aop:config> 元素内部。对于每个切面而言,都要创建一个<aop:aspect> 元素来为具体的切面实现引用后端bean 实例。 切面bean 必须有一个标识符,供<aop:aspect> 元素引用。   3.声明切入点 切入点使用<aop:pointcut> 元素声明。 切入点必须定义在<aop:aspect> 元素下,或者直接定义在<aop:config> 元素下。 定义在<aop:aspect> 元素下:只对当前切面有效   定义在<aop:config> 元素下:对所有切面都有效 基于XML AOP 配置不允许在切入点表达式中用名称引用其他切入点。   4.声明通知 l   aop 名称空间中,每种通知类型都对应一个特定的XML 元素。 l   通知元素需要使用<pointcut-ref> 来引用切入点,或用<pointcut> 直接嵌入切入点表达式。 l  method 属性指定切面类中通知方法的名称 5.完整配置如下:   <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置 bean --> <bean id="arithmeticCalculator" class="com.atguigu.spring.aop.xml.ArithmeticCalculatorImpl"></bean> <!-- 配置切面的 bean. --> <bean id="loggingAspect" class="com.atguigu.spring.aop.xml.LoggingAspect"> </bean> <bean id="vlidationAspect" class="com.atguigu.spring.aop.xml.VlidationAspect"> </bean> <!-- 配置 AOP --> <aop:config> <!-- 配置切点表达式 --> <aop:pointcut expression="execution(* com.atguigu.spring.aop.xml.ArithmeticCalculator.*(int, int))" id="pointcut"/> <!-- 配置切面及通知 --> <aop:aspect ref="loggingAspect" order="2"> <aop:before method="beforeMethod" pointcut-ref="pointcut"/> <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/> <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/> <!-- <aop:around method="aroundMethod" pointcut-ref="pointcut"/> --> </aop:aspect> <aop:aspect ref="vlidationAspect" order="1"> <aop:before method="validateArgs" pointcut-ref="pointcut"/> </aop:aspect> </aop:config> </beans>
转载请注明原文地址: https://www.6miu.com/read-2000030.html

最新回复(0)