Aspect-oriented Spring
- AOP
- Spring 给你的 5 种建议
Before
After
After-returning
After-throwing
Around
- Spring 与 AspectJ
- Classic Spring proxy-based AOP
- Pure-POJO aspects
@AspectJ annotation-driven aspects
- Injected AspectJ aspects (available in all versions of Spring)
- 使用 pointcuts 选择 join points
AspectJ 的 designator
- args()
- @args()
- execution()
- this()
- target()
- @target()
- within()
- @within()
- @annotation
- 书写 pointcuts
execution(* concert.Performance.perform(..))
- execution: 在方法运行期间执行
*: 返回任意类型
concert.Performance: 方法属于什么类型
perform: 方法名
- ..: 传入参数
execution(* concert.Performance.perform(..)) && within(concert.*))
&&: 组合 operator
within(concert.*): 当这个方法在 concert 包下面的任意一个类中被调用的时候
execution(* concert.Performance.perform()) and bean('woodstock')
- 执行 beanId='woodstock' 类中的方法
execution(* concert.Performance.perform()) and !bean('woodstock')
- 创建 annotated aspects
@Aspect 作用于类
- `@Before("execution( concert.Performance.perform(..))")`** 作用于方法
- `@After("execution( concert.Performance.perform(..))")`** 作用于方法
- 使用 `@Pointcut("execution( concert.Performance.perform(..))")
** 作用域performance()` 方法上
- 使用
@Before("performance()") 改进
- 打开 auto-proxying
- JavaConfig
- XMLConfig
<aop:aspectj-autoproxy />
- 创建 around advice
@Around("performance()")
- 参数
ProceedingJoinPoint.proceed()
- 处理参数
@Pointcut("execution(* soundsystem.CompactDisc.playTrack(int)) " + "&& args(trackNumber)")
@Before("trackPlayed(trackNumber)")
- Annotating Introductions
- 利用 Spring AOP,你可以为一个 Bean 引入新方法
- 一个 Proxy 拦截了 calls ,然后 delegates 给不同的实现对象
- 一个
@Aspect 不提供 @Before、@After
- 提供
@DeclareParents(value="concert.Performance+", defaultImpl=DefaultEncoreable.class)
value: 应该被 interface introduced 的 beans
- +: 任何
Performance 的子类型
<bean class="concert.EncoreableIntroducer" />
- 在 XML 中声明 aspects
<aop:config>
<aop:aspect ref="audience">
- Injecting AspectJ aspects