在Spring的AOP命名空间中,提供了多个元素用来在XML中声明切面,如下图所示:
重新看之前提过的Audience类,将AspectJ注解全部移除:
package main.java; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; /** * @author [email protected] * @date 18-4-18 上午8:56 */ public class Audience { public void silenceCellPhones(){ System.out.println("Silecing cell phones"); } public void takeSeats(){ System.out.println("Taking seats"); } public void applause(){ System.out.println("CLAP CLAP CLAP"); } public void demandRefund(){ System.out.println("Demanding a refund"); } }
声明前置和后置通知:
<aop:config> <aop:aspect ref="Audience"> <aop:before pointcut="execution(* main.java.Performance.perform(..))" method="silenceCellPhones"/> <aop:before pointcut="execution(* main.java.Performance.perform(..))" method="takeSeats"/> <aop:after-returning pointcut="execution(* main.java.Performance.perform(..))" method="applause"/> <aop:after-throwing pointcut="execution(* main.java.Performance.perform(..))" method="demandRefund"/> </aop:aspect> </aop:config>
大多数的AOP配置元素必须在<aop:config>元素的上下文内使用;这条规则有几种例外场景,但把bean声明为一个切面时,总是以<aop:config>元素开始配置.
在基于AspectJ注解的通知中,当发现pointcut属性的重复时,可以使用<aop:pointcut>元素:
<aop:pointcut id="performance" expression="execution(* main.java.Performance.perform(..))"/> <aop:before pointcut-ref="performance" method="silenceCellPhones"/>声明环绕通知:
<aop:around method="watchPerformance" pointcut-ref="performance"/>与其他通知的XML元素一样,需要制定一个切点和通知方法的方法名.