Spring----学习(17)----基于配置文件的方式来配置AOP

 1. 除了使用 AspectJ 注解声明切面, Spring 也支持在 Bean 配置文件中声明切面.

      这种声明是通过 aop schema 中的 XML 元素完成的.

 2. 正常情况下, 基于注解的声明要优先于基于 XML 的声明. 通过 AspectJ 注解, 切面可以与 AspectJ 兼容,

     而基于 XML 的配置则是 Spring 专有的. 由于 AspectJ 得到越来越多的 AOP 框架支持,

      所以以注解风格编写的切面将会有更多重用的机会.

3.  当使用 XML 声明切面时, 需要在 <beans> 根元素中导入 aop Schema

 4.Bean 配置文件中, 所有的 Spring AOP 配置都必须定义在 <aop:config> 元素内部.

    对于每个切面而言, 都要创建一个 <aop:aspect> 元素来为具体的切面实现引用后端 Bean 实例.

5.切面 Bean 必须有一个标示符, <aop:aspect> 元素引用(id属性)

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

<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

     <!-- 配置bean -->
	<bean id="arithmeticCalculator" class="com.lishenhuan.aop.impl.copy.ArithmeticCalculatorImpl"></bean>
	<!-- 配置切面的bean -->
	<bean id="log" class="com.lishenhuan.aop.impl.copy.Log"></bean>
	<bean id="check" class="com.lishenhuan.aop.impl.copy.Check"></bean>
	<!-- 配置AOP -->
	<aop:config>
		<!-- 配置切点表达式 -->
		<aop:pointcut expression="execution(*  com.lishenhuan.aop.impl.copy.ArithmeticCalculator.*(int , int )) " id="pointCut"/>
	    <!-- 配置切面及通知-->
	    <aop:aspect ref="log" order="2">
	    		<aop:before method="before"  pointcut-ref="pointCut"/>
	    		<aop:after method="after" pointcut-ref="pointCut"/>
	    		<aop:after-returning method="afterReturning" pointcut-ref="pointCut" returning="result"/>
	    		<aop:after-throwing method="afterThrowing" pointcut-ref="pointCut" throwing="ex"/>
	    </aop:aspect>
	      <aop:aspect ref="check" order="1">
	    		<aop:before method="before"  pointcut-ref="pointCut"/>
	    </aop:aspect>
	</aop:config>
</beans>

猜你喜欢

转载自blog.csdn.net/lsh15846393847/article/details/88995543