Spring_AOP之Annotation
@AspectJ简介
@AspectJ使用了java5的注解,可以将切面声明为普通的java类。
启用@AspectJ支持
基于XML格式的配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 8 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 9 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> 10 11 <!-- <bean/> definitions here --> 12 13 14 15 </beans>
启用
1 <aop:aspectj-autoproxy/>
基于DTD的配置文件
你仍然可以通过在你的application context中添加如下定义来启用@AspectJ支持:
1 <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
你需要在你的应用程序的classpath中引入两个AspectJ库:aspectjweaver.jar和aspectjrt.jar。
声明一个切面
启用@AspectJ支持后,在application context中定义的任意带有一个@Aspect切面(拥有@Aspect
注解)的bean都将被Spring自动识别并用于配置Spring AOP。
application context中一个常见的bean定义,它指向一个使用了@Aspect注解的bean类:
1 <bean id="myAspect" class="org.xyz.NotVeryUsefulAspect"> 2 3 <!-- configure properties of aspect here as normal --> 4 5 </bean>
以及NotVeryUsefulAspect类的定义,使用了 org.aspectj.lang.annotation.Aspect注解。
1 package org.xyz; 2 3 import org.aspectj.lang.annotation.Aspect; 4 5 6 7 @Aspect 8 9 public class NotVeryUsefulAspect { 10 11 12 13 }
声明一个切入点(pointcut)
1 @Pointcut("execution(* transfer(..))")// the pointcut expression 2 3 private void anyOldTransfer() {}// the pointcut signature
拦截execution - 匹配方法执行的连接点,这是你将会用到的Spring的最主要的切入点指示符。
-切入点简介
-切入点的匹配表达式
-execution pointcut表达式
-实例
声明通知(advice)
Before advice
After advice
Around advice
Throwing advice