AOP专题

Spring的AOP实现之二

上页

  Advice生命周期

  1. Per-class advice是经常使用,适合普通的Advice,如transaction advisors ,这并不依赖被代理对象的状态或需要增加新状态。
  2. Per-instance advice 适合introductions ,支持Mixin,在这种情况下,advice要加入一些状态到被代理的对象中。

Advice类型:

Advice类型Spring内部机制

环绕Around advice : 最基本的类型,

public interface MethodInterceptor extends Interceptor {
Object invoke(MethodInvocation invocation) throws Throwable;
}

前置Before:

class A implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object target) throws Throwable {
// TODO Auto-generated method stub
}
}

示意图:

应用案例:

下面看看如何使用元注解实现AOP。

元注解

  • 从Spring2.0开始
    支持@AspectJ注解,依然是方法级
    无缝集成AspectJ
    基于Schema的配置支持,提供了aop命名空间
  • 依赖的类库
    asm-2.2.2.jar,asm-commons-2.2.2.jar,asm-util-2.2.2.jar.
    aspectjrt.jar,aspectjweaver.jar

与配置对比:

  • 编码

    @Aspect
    public class HelloFromAspectJ {
           @Before(“execution(* greetTo(..))")
           public void sayHello() {
                  System.out.println("Hello from                      AspectJ!");
           }
    }


  • 配置
    <aop:aspectj-autoproxy>

元注释中*等通配符说明:

  1. * 匹配任意字符,但它只能匹配上下文中的一个元素;
  2. .. 匹配任意字符,可以匹配上下文中的多个元素,但在表示类时,必须和*联合使用,而在表示入参时则单独使用;
  3. + 表示按类型匹配指定类的所有类,仅能跟在类名后面。

前置元注释:

后置元注释:

后置Throw处理(处理Exception)

环绕处理:

class C implements MethodInterceptor{
public Object invoke(MethodInvocation arg0) throws Throwable {
// TODO Auto-generated method stub
return null;
}
}

XML配置和元注解对比:

 

下页

Spring专题