AspectJ深入学习

AspectJ是AOP编程的实现产品。但是其实现机制是基于其自身的编织器实现大的。

Spring的事务管理是基于JDK的动态代理/CGLIB实现。而其AOP编程也是基于AspectJ实现的,这也就是为什么在使用spring的AOP时,需要将aspectj相关库引入到类路径下。

也就是说AOP现在有两种机制----SpringFramework’s Proxy-based  and Aspectj’s weaver-based.

切入点(Pointcut)可以分为命名的(named)和匿名的(anonymous)两种类型。这里只介绍命名类型的。见下图:

未命名2

实例:

pointcut greeting() : execution(* Hello.sayHello(..));

切入点操作符:

一元操作符: !(unary negation operator)

二元操作符: &&   and ||   (biary operation)

签名(signature)语法:

pointcut named() : execution("public * one.two..hello*.insert*(int,..)")

拦截下来方法是public类型,返回值无所谓,必须是one.two下的类或者是其子包下的类,方法所在的类必须以hello开头。并且方法名要以insert开头。方法参数类型第一个为int类型,其余的无所谓。

星号(*)-----用来匹配两个句点之间任意个数个字符。

两个句点(..)------用来匹配任意个数个字符。这也包括两个句点之间的内容。

 

 

类型签名样式介绍:

类型可以有很多-例如: 类、接口、注解、主类型、在ASpectJ甚至也会包含切面。在类型签名中可以使用一元、二元等操作符。

在传统的用法中,如果没有指定全名的话,那么就会从当前切面所在的类进行查找。如果是使用的注解的方法来定义切面的话,那么要使用全名去限定类型所在的包。

 

 

切入点定义实例:

pointcut named() : execution("public * !@(annotationOne&&annotationTwo) one.two..hello*.insert*(int,..)")

pointcut named() : execution("public * !@(annotationOne||annotationTwo) one.two..hello*.insert*(int,..)")

pointcut named() : execution("modifier * !@(annotationOne||annotationTwo) one.two..hello*.insert*(int,..)")

modifier可以是 public /private/protected/static/final/@annotation

通常情况,adivce 是没有名字的。因为我们不会直接去调用它。
advice可以拥有名字、参数、抛出的异常类型。在advice里,可以拥有各种各种的在方法里面出现过的控制结构。可以通过this来引用aspect实例。环绕通知需要一个返回类型。

advice不能直接被调用。所以没有修饰符等。名字是可选的,而方法的名字是必须有的。在before和after advice中不可以有返回值类型。advice可以返回this、thisJoinPart、thisJoinPointStaticPart、thisEnclosingJoinPointStaticPart等特殊对象。around advice可以通过proceed()方法继续进行.

你可能感兴趣的:(AspectJ深入学习)