日期:2014-05-17  浏览次数:20876 次

跟我学aspectj之四 ----- pointcut基础语法

一、aspect的定义

   运行完HelloWorld以后,我们来看下aspect的基础语法:

1、定义一个切面: 关键字aspect。 这定义Java类的语法类似。

2、定义pointcut:  [修饰符(public,protected.....)] pointcut poincut名字() : 表达式;

3、定义advice:   通知类型() : pointcut名字(){ .......逻辑}

?

   一个最基本的aspect,就是这样组成的。值得一提的是:aspectj支持很多类型的pointcut,最基本的就是method call pointcut(方法级别),而Spring的aop 仅支持method call pointcut。所以,在后面陆续的使用中,你将会发现aspectj的强大, 简直强大到有点过分。而至于advice,aspectj也一样,就是5种类型。

?

?

?

二、pointcut的主要类型

Methods and Constructors
call(Signature) every call to any method or constructor matching Signature at the call site(方法和构造函数的调用点)
execution(Signature) every execution of any method or constructor matching Signature (方法和构造函数的执行点)
Fields
get(Signature) every reference to any field matching Signature   (属性的读操作)
set(Signature) every assignment to any field matching Signature. The assigned value can be exposed with anargs pointcut (属性的写操作)
Exception Handlers
handler(TypePattern) every exception handler for any Throwable type in TypePattern. The exception value can be exposed with anargs pointcut(异常处理执行)
Advice
adviceexecution() every execution of any piece of advice(Advice执行)
Initialization
staticinitialization(TypePattern) every execution of a static initializer for any type in TypePattern (类初始化)
initialization(Signature) every initialization of an object when the first constructor called in the type matchesSignature, encompassing the return from the super constructor call to the return of the first-called constructor (对象初始化)
preinitialization(Signature) every pre-initialization of an object when the first constructor called in the type matchesSignature, encompassing the entry of the first-called constructor to the call to the super constructor (对象预先初始化)
Lexical
within(TypePattern) every join point from code defined in a type in TypePattern (捕获在指定类或者方面中的程序体中的所有连接点,包括内部类)
withincode(Signature) every join point from code defined in a method or constructor matching Signature (用于捕获在构造器或者方法中的所有连接点,包括在其中的本地类)
Instanceof checks and context exposure
this(Type or Id) every join point when the currently executing object is an instance of Type orId's type(所有Type or id 的实例的执行点,匹配所有的连接点,如方法调用,属性设置,当前的执行对象为Account,或者其子类。)
target(Type or Id) every join point when the target executing object is an instance of Type orId's type (配所有的连接点,目标对象为Type或Id)