一.静态横切
动态横切改变程序的行为,静态横切改变程序数据类型(class,interface,aspect)的结构和织入时行为
静态横切分为三类:Inter-Type declaration,Weave-time error and warning declarations 、Exception softening
1)Inter-type declaration
通过一种类型(aspect)为另一种类型(interface、class、甚至是aspect)提供声明。包括成员引入(Member-Introduction),类型结构更改(Type-Hierarchy Modification)和注解补充等支持。
2)Weave-time error and warning declarations
检测织入时连接点处错误和警告的存在。
3)Exception softening
使用横切的方法处理checked exception
二.静态横切详解
1) 成员引入(Member-Introduction)
语法实例:
a. private PropertyChangeSupport Customer.propertyChangeSupport;
向Customer类中引入private PropertyChangeSupport propertyChangeSuppor成员, 但在引入它的Aspect中可以直接访问
b. public void Customer.addPropertyChangeListener(PropertyChangeListener listener) {...} 向Customer类中引入方法
成员引入规则:
1)切面只能引入public或者private的成员。当修饰符是public时,成员对其他类和切面是可见的;
当修饰符是private时,成员只对引入该成员的aspect可见。当使用private 引入时,实际织入的成员名称是mangled version的
2)多个aspect可以引入名字相同的private成员,但是不能引入名字相同的public成员
3)aspect可以向类或者借口中引入字段(final或者non-final的)、方法、构造器。
4)如果一个类中有一个方法,aspect向其父类中引入了相同签名的方法,则在子中使用子类方法的实现
5)一个成员引入的声明只能用于一个类型。例如:以下用通配符的声明是不允许的: private PropertyChangeSupport *.propertyChangeSupport
2) 改变类型的层次结构(Modifying the type hierarchy)
可用于改变已存在的类或接口的层次结构
语法规则:
declare parents : [TypePattern] implements [InterfaceList];
declare parents : [TypePattern] extends [Class or InterfaceList];
实例:
declare parents: banking.entities.* implements BeanSupport;
banking.entities 包下的所有类实现BeanSupport接口
declare parents: @Entity * implements BeanSupport;
声明所有加@Entity注解的类实现BeanSupport
3)为多个类型引入成员(Introducting members to multple Types):
实现方式:通过使用中间接口。
4) 提供注解:
可以给方法、字段、构造器、类引入注解
实例:
declare @method: * AccountService.*(..): @Transactional(Propagation.Required);
给所有的AccountService类的方法加入@Transactional(Propagation.Required)注解
declare @constructor: AccountService+.new(): @ConfigurationOnly;
为AccountSerivce及其子类的无参构造器加上@ConfigurationOnly注解
declare @field: * MissileInformation.*: @Classified;
为MissileInformation类的所有字段加上 @Classified注解
declare @type: banking..* : @PrivacyControlled;
为banking直接和间接子包下的类加上@PrivacyControlled注解
5)声明织入时错误和警告(Declaring weave-time errors and warnings):
满足某pointcut的joinpoint处时会抛出异常或者警告
注意:这种机制影响的是编译时的行为,所以不能用于runtime的pointcut,
例如:this(), target(), args(), @this(), @target(), @args(), if(), cflow(), and cflowbe-low()
语法:
declare error : <pointcut> : <message>;
declare warning : <pointcut> : <message>;
6)软化受检异常(Softening checked exceptions)
使你处理某些pointcut抛出的checked exception像unchecked exception一样处理,即不用try catch 语句或者throws
语法:
declare soft : <ExceptionTypePattern> : <pointcut>;