AspectJ 中跨类型声明的深入解析
1. AspectJ 系统设计与跨类型声明概述
AspectJ 能够让我们设计出在构建时支持行为分层组合的系统,但组件与切面之间过度的相互依赖会阻碍这种设计。不过,AspectJ 的作用域规则允许存在其他代码无法访问的跨类型成员,这使得切面能够控制其他代码对其引入到某个类型上的行为的依赖程度。
2. 引入与通知示例
在处理对象状态持久化到数据库的需求时,传统方法存在问题。以 Employee
类为例,为了与第三方持久化框架协作, Employee
类需要实现 store()
方法,并且要谨慎地仅在状态改变时进行数据持久化。在面向切面编程(AOP)之前,通常的做法是在字段改变时手动更新一个脏标志(dirty flag),代码如下:
/* manually adding an update to the dirty flag */
public void raiseSalary(int increment){
dirty = true;
salary += increment;
}
/**
* Uses the dirty flag to avoid expensive
* database updates.
*/
public void Employee.store(){
if(dirty){
//update row in database
}
dirty = false;
}
<