AOP的本质还是动态代理对方法调用进行增强。Spring 提供了方便的注解实现自定义切面Aspect。
1、概念:
切面: @Aspect
切点: @Pointcut、
建言: @Before/@After/@Around/@AfterReturning/@AfterThrowing
2、Pointcut expression表达式规则
Pointcut可以有下列方式来定义或者通过通配符 && || ! 进行组合
- args()、@args()
- execution()
- target() 、@target()
- within()、@within()
- @annotation
- this()
- @within和@target针对类的注解, @annotation是针对方法的注解
带有 @Transactional 标注的 所有类 下的任意方法.
@within(org.springframework.transaction.annotation.Transactional)
@target(org.springframework.transaction.annotation.Transactional)带有 @Transactional 标注的任意 方法
@annotation(org.springframework.transaction.annotation.Transactional)
- execution
任意公共方法执行:
execution(public * *(..))定义在service包里的任意方法:
execution(* com.xyz.service.*.*(..))定义在service包和所有子包里的任意类的任意方法的执行:
execution(* com.xyz.service..*.*(..))任何一个以 set 开头的方法:
execution(* set*(..))定义在 exp包和所有子包里的ObjP2类的任意方法的执行:
execution(* com.test.spring.aop.exp..ObjP2.*(..))")
- within与target类似
pointcutexp包里的任意类
within(com.test.spring.aop.pointcutexp.*)
pointcutexp包和所有子包里的任意类.
within(com.test.spring.aop.pointcutexp..*)
参数带有 @Transactional 标注的方法
@args(org.springframework.transaction.annotation.Transactional)
参数为String类型的方法(运行时决定)
args(String)
实现了Intf接口的所有类,如果Intf不是接口,限定Intf单个类.
当一个实现了接口的类被AOP的时候,用getBean方法必须cast为接口类型,不能为该类的类型.this(com.test.spring.aop.pointcutexp.Intf)