类型声明可以容易地转移到新风格,如清单 12 所示:
清单 12. 简化的生命周期管理器方面,注释风格
/**
* This aspect provides default lifecycle management for all
* types with the @ManagedComponent annotation.
*/
@Aspect
public class 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();
}
...
AOP@Work:介绍AspectJ 5 - AspectJ中的Java 5支持和其他新特性抢鲜看(12)
时间:2011-09-04 IBM Adrian Colyer
与切入点和建议一起使用注释
下面,我们来看看用 @AspectJ 风格重写切入点和建议时发生了什么。切入点 是在与切入点具有相同签名的 void方法上使用 @Pointcut注释而编写的。建议则 是在方法上使用 @Before、 @Around、@AfterReturning、@AfterThrowing和 @After注释而编写的,如清单 13 所示:
清单 13. 注释风格的切入点和建议
/**
* This aspect provides default lifecycle management for all
* types with the @ManagedComponent annotation.
*/
@Aspect
public class LifecycleManager {
...
// these pointcuts capture the lifecycle events of managed components
@Pointcut(
"execution(* org.aspectprogrammer.devWorks.LifecycleManager
.Lifecycle.initialize(..))
&& this(l)"
)
void initializing(Lifecycle l) {}
@Pointcut(
"execution(* org.aspectprogrammer.devWorks.LifecycleManager
.Lifecycle.starting(..))
&& this(l)"
)
void starting(Lifecycle l){}
@Pointcut(
"execution(* org.aspectprogrammer.devWorks.LifecycleManager
.Lifecycle.stopping(..))
&& this(l)"
)
void stopping(Lifecycle l) {}
@Pointcut(
"execution(* org.aspectprogrammer.devWorks.LifecycleManager
.Lifecycle.terminating(..))
&& this(l) "
)
void terminating(Lifecycle l) {}
/**
* Ensure we are in the initial state before initializing.
*/
@Before("initializing(managedComponent)")
public void moveToInitializingState(Lifecycle 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.
*/
@AfterReturning("initializing (managedComponent)")
public void moveToInitializedStated (Lifecycle managedComponent) {
managedComponent.state = State.INITIALIZED;
}
注意,在切入点表达式中,任何引用的类型都必须是全限定的(导入语句只能 在源代码条件下存在,在处理注释时,对织入器不可用)。建议方法必须声明成 public,并返回 void (@Around建议除外,它必须返回值)。
AOP@Work:介绍AspectJ 5 - AspectJ中的Java 5支持和其他新特性抢鲜看(13)
时间:2011-09-04 IBM Adrian Colyer
与类型间声明一起使用注释
现在剩下的就是把类型间声明也转移到 @AspectJ 风格的方面了。在注释风格 中,这些声明像清单 14 所示这样进行 |