-
首先要在头部添加aop命名空间
<?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.xsd">
-
Xml和JavaConfig的对应关系
<aop:aspectj-autoproxy> @EnableAspectJAutoProxy
<aop:config> 顶层配置元素,绝大多数的<aop:xxx>都要套在这个元素下面
<aop:aspect> @Aspect
<aop:after> @Afer
<aop:after-returning> @AfterReturning
<aop:after-throwing> @AfterThrowing
<aop:around> @Around
<aop:before> @Before
使用Xml配置,通知类无需添加任何注解(例如 @Aspect),只需要在xml中配置
-
示例
<?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.xsd"> <bean id="volunteer" class="com.springinaction.springidol.Volunteer"/> <bean id="magician" class="com.springinaction.springidol.Magician"/> <aop:config> <aop:aspect ref="magician"> <aop:before method="interceptThoughts" arg-names="thoughts, people" pointcut="execution(* com.springinaction.springidol.Thinker.thinkOfSomething(String, String)) and args(thoughts, people)"/> </aop:aspect> </aop:config> </beans>
说明
(1) <aop:config>是定义切面的根元素,它也要嵌套进 <beans>下
(2) 使用切面类,也要声明切面类的bean
(3) <aop:aspect ref="magician">用于声明一个切面,ref用于指向切面类的id
(4) 能够成为切面的类必须是具体的实现类,不能是接口
(5) <aop:before>(其他4种通知时刻类型同理)包括了几种属性
pointcut代表切点函数
args代表方法参数名字(要匹配)
method代表通知的方法
arg-names代表通知方法的参数名字
(6) 不同切点表达式之间用 and,or,not连接(JavaConfig使用 &&,||,!)
11-02