8.4.6 基于XML配置文件的管理方式 3. 配置切入点
类似于@AspectJ方式,允许定义切入点来重用切入点表达式,XML配置方式也可通过定义切入点来重用切入点表达式。
Spring提供了<aop:pointcut>元素来定义切入点。
- 当把<aop:pointcut>元素作为<aop:config>的子元素定义时,表明该切入点可被多个切面共享;
- 当把<aop:pointcut>元素作为<aop:aspect>的子元素定义时,表明该切入点只能在该切面中有效。
配置<aop:pointcut>元素时通常需要指定如下两个属性:
| 属性 | 描述 | 
| id | 指定该切入点的标识名。 | 
| expression | 指定该切入点关联的切入点表达式。 | 
定义切入点
如下配置片段定义了一个简单的切入点:
| 12
 3
 
 | <aop:pointcut id="myPointcut"
 expression="execution(* org.crazyit.app.service.impl.*.*(..))" />
 
 | 
上面的配置片段既可作为<aop:config>的子元素,用于配置全局切入点;
也可作为<aop:aspect>的子元素,用于配置仅对该切面有效的切入点。
在XML配置中引用在注解定义的切入点
除此之外,如果要在XML配置中引用使用注解定义的切入点,在<aop:pointcut>元素中指定切入点表达式时还有另外一种用法,看如下配置片段:
| 12
 3
 4
 5
 6
 7
 
 | <aop:config>...
 
 <aop:pointcut id="myPointcut"
 expression="org.crazyit.SystemArchitecture.myPointcut()"/>
 ...
 </aop:config>
 
 | 
程序示例
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | E:\workspace_QingLiangJiJavaEEQiYeYingYongShiZhang5\XML-AfterThrowing└─src\
 ├─beans.xml
 ├─lee\
 │ └─BeanTest.java
 └─org\
 └─crazyit\
 └─app\
 ├─aspect\
 │ └─RepairAspect.java
 └─service\
 ├─Hello.java
 ├─impl\
 │ ├─HelloImpl.java
 │ └─WorldImpl.java
 └─World.java
 
 | 
下面的示例程序定义了一个AfterThrowing增强处理,包含该增强处理的切面类如下。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | package org.crazyit.app.aspect;
 public class RepairAspect
 {
 
 
 public void doRecoveryActions(Throwable ex)
 {
 System.out.println("目标方法中抛出的异常:" + ex);
 System.out.println("模拟Advice对异常的修复...");
 }
 }
 
 | 
与前面的切面类完全类似,该Java类就是一个普通的Java类。下面的配置文件将负责配置该Bean实例,并将该Bean实例转换成切面Bean。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | <?xml version="1.0" encoding="GBK"?><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.xsd">
 
 <bean id="afterThrowingAdviceBean"
 class="org.crazyit.app.aspect.RepairAspect" />
 <bean id="hello" class="org.crazyit.app.service.impl.HelloImpl" />
 <bean id="world" class="org.crazyit.app.service.impl.WorldImpl" />
 <aop:config>
 
 <aop:pointcut id="myPointcut"
 expression="execution(* org.crazyit.app.service.impl.*.*(..))" />
 <aop:aspect id="afterThrowingAdviceAspect"
 ref="afterThrowingAdviceBean">
 
 <aop:after-throwing
 pointcut-ref="myPointcut" method="doRecoveryActions"
 throwing="ex" />
 </aop:aspect>
 </aop:config>
 </beans>
 
 | 
上面配置文件中配置了一个全局切入点myPointcut,这样其他切面Bean就可多次复用该切入点了。上面的配置文件在配置<aop:after-throwing>元素时,使用pointcut-ref引用了一个已有的myPointcut这个切入点。
原文链接: 8.4.6 基于XML配置文件的管理方式 3. 配置切入点