乏显示横切结构的视 图),它们也为日常的编辑体验造成显著区别。
需要注意的重点是,AspectJ 5 发行版具有以下内容(虽然有两种开发风格) :
一个 语言
一个 语义
一个 织入器
不论选择用什么风格表达方面,它们实际表达的都是同样的东西,而且也用同 样的方式发挥作用。这一重要属性使得可以容易地混合和匹配风格(所以用 @AspectJ 风格开发的方面可以与用代码风格开发的方面结合使用,反之亦然)。 但是 @AspectJ 风格有些限制。例如,在使用常规的 Java 编译器时,就不支持 注释风格版本的 AspectJ 构造(例如 declare soft),因为这类构造需要编译 时支持而不是织入时支持。
现在来看一个使用 @AspectJ 注释的示例。
用 @AspectJ 注释编写方面
我先从清单 11 显示的简化的 LifecycleManager 方面开始,并用 @AspectJ 风格重写它:
清单 11. 简化的生命周期管理器方面,代码风格
/**
* This aspect provides default lifecycle management for all
* types with the @ManagedComponent annotation.
*/
public aspect LifecycleManager {
/**
* The defined states that a managed component can be in.
*/
public enum State {
INITIAL,
INITIALIZING,INITIALIZED,
STARTING,STARTED,
STOPPING,
TERMINATING,TERMINATED,
BROKEN;
}
/**
* The lifecycle interface supported by managed components.
*/
public interface Lifecycle {
void initialize();
void start();
void stop();
void terminate();
boolean isBroken();
State getState();
}
/**
* Any type with an @ManagedComponent annotation implements
* the Lifecycle interface (and acquires the default implementation
* defined in this aspect if none is provided by the type).
*/
declare parents : @ManagedComponent * implements Lifecycle;
// default implementations for the state-based lifecycle events
private State Lifecycle.state = State.INITIAL;
public void Lifecycle.initialize() {}
public void Lifecycle.start() {}
public void Lifecycle.stop() {}
public void Lifecycle.terminate() {}
public boolean Lifecycle.isBroken() { return state == State.BROKEN; }
public State Lifecycle.getState () { return state; }
// these pointcuts capture the lifecycle events of managed components
pointcut initializing (Lifecycle l) : execution(* Lifecycle.initialize(..)) && this (l);
pointcut starting(Lifecycle l) : execution(* Lifecycle.starting(..)) && this(l);
pointcut stopping (Lifecycle l) : execution(* Lifecycle.stopping(..)) && this (l);
pointcut terminating(Lifecycle l): execution(* Lifecycle.terminating(..)) && this(l);
/**
* Ensure we are in the initial state before initializing.
*/
before(Lifecycle managedComponent) : initializing(managedComponent) {
if (managedComponent.state != State.INITIAL)
throw new IllegalStateException("Can only initialize from INITIAL state");
managedComponent.state = State.INITIALIZING;
}
/**
* If we successfully initialized the component, update the state and
* notify all observers.
*/
after(Lifecycle managedComponent) returning : initializing(managedComponent) {
managedComponent.state = State.INITIALIZED;
}
...
}
AOP@Work:介绍AspectJ 5 - AspectJ中的Java 5支持和其他新特性抢鲜看(11)
时间:2011-09-04 IBM Adrian Colyer
方面声明和内部的 |