Spring AOP的一點總結

1. Spring AOP介紹

AOP(Aspect-Oriented Programming),面向切面的編程,是OOP(面向對象的編程)的重要補充,所謂AOP,就是在執行Java類中的方法前或后加入自定義方法。Spring AOP是Spring的一個重要組成部分,和IoC并稱為Spring的兩大基礎組件。關于Spring Ioc可以訪問http://www.lxweimin.com/p/6178ba063553

spring-aop.png

1.1 小明搬磚的故事

小明每天都要上班、搬磚、下班。現在,小明的老婆每天在他上班搬磚之前,檢查他是否帶了公交卡;小明的兒子每天在搬磚下班之后討要零花錢。小明只管搬磚掙錢即可,老婆檢查公交卡和兒子討要零花錢對搬磚掙錢這個事不會產生任何影響,該掙多少錢還掙多少錢;只是搬磚回來后,兒子會討要零花錢,減少小明掙到的工資。

接下來我們使用OOP和AOP的思想來考慮小明搬磚的故事。根據OOP的思想,小明就是一個對象,他具有上班、搬磚、下班等三個行為。根據AOP的思想,小明老婆在小明執行搬磚掙錢前做出門檢查,小明兒子在小明執行搬磚掙錢后討要零花錢,這兩者都不會改變小明調用搬磚掙錢的方法,但可能會影響其結果。


1.2 AOP使用的場景

AOP用來封裝橫切關注點,具體可以在下面的場景中使用。

  • Authentication 權限
  • Caching 緩存
  • Context passing 內容傳遞
  • Error handling 錯誤處理
  • Lazy loading 懶加載
  • Debugging  調試
  • logging,tracing,profiling and monitoring 記錄跟蹤 優化 校準
  • Performance optimization 性能優化
  • Persistence  持久化
  • Resource pooling 資源池
  • Synchronization 同步
  • Transactions 事務

1.3 AOP的相關概念

1. 切面(Aspect):切面是通知和切點的結合。通知和切點共同定義了切面的全部內容———他是什么,在何時和何處完成其功能。

2. 通知(Advice):在AOP中,切面的工作被稱為通知。通知定義了切面“是什么”以及“何時”使用。除了描述切面要完成的工作,通知還解決了何時執行這個工作的問題。Spring切面可以應用5種類型的通知:

  • 前置通知(Before):在目標方法被調用之前調用通知功能
  • 后置通知(After):在目標方法完成之后調用通知,此時不會關心方法的輸出是什么
  • 返回通知(After-returning):在目標方法成功執行之后調用通知
  • 異常通知(After-throwing):在目標方法拋出異常后調用通知
  • 環繞通知(Around):通知包裹了被通知的方法,在被通知的方法調用之前和調用之后執行自定義的行為

3. 切點(Pointcut):如果說通知定義了切面“是什么”和“何時”的話,那么切點就定義了“何處”。比如我想把日志引入到某個具體的方法中,這個方法就是所謂的切點。

4. 連接點(Join Point):程序執行過程中明確的點,如方法的調用或特定的異常被拋出。在Spring AOP中,一個連接點總是表示一個方法的執行。

5. 引入(Introduction):添加方法或字段到被通知的類。 Spring允許引入新的接口到任何被通知的對象。例如,你可以使用一個引入使任何對象實現 IsModified接口,來簡化緩存。Spring中要使用Introduction, 可有通過DelegatingIntroductionInterceptor來實現通知,通過DefaultIntroductionAdvisor來配置Advice和代理類要實現的接口。

6. 織入(Weaving):把切面應用到目標對象來創建新的代理對象的過程添加方法或字段到被通知的類。這可以在編譯時完成(例如使用AspectJ編譯器),也可以在運行時完成。Spring AOP,在運行時完成織入。

7. 目標對象(Target Object): 包含連接點的對象。也被稱作被通知或被代理對象。

8. AOP代理(AOP Proxy): AOP框架創建的對象,包含通知。 在Spring中,AOP代理可以是JDK動態代理或者CGLIB代理,本文會在下文講述這兩種動態創建代理的方式。

2. 基于@Aspect的AOP編程實踐

本節通過一個簡單的例子,說明如何實現基于@Aspect的AOP編程實踐。我們將在Controller執行方法的前后,輸出一些日志。

2.1 pom.xml中引入AOP

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

2.2 HelloController

這個Controller就是我們選定的目標對象(Target Object),它的hello()方法就是連接點(Join Point)。

@RestController
public class HelloController {

  @RequestMapping(value = "/hello")
  public String hello(@RequestParam(value = "name", required = true) String name) {
    String result = "hello  " + name;
    System.out.println(result);
    return result;
  }

}

2.3 ApiAspect切面

@Component // 注冊到Spring容器
@Aspect // 該注解標示該類為切面類,切面是由通知和切點組成的。
public class ApiAspect {
  
  //雙引號中間的內容是PointCut(切點)表達式。@Before是前屬通知
  @Before("execution(* com.example.controller.HelloController.*(..))")  
  public void before(){
    System.out.println("方法執行前執行.....before");  
  }

  //@Around是環繞通知,下面的通知看注解即可,不再寫注釋。
  @Around("execution(* com.example.controller.HelloController.*(..))")  
  public String around(ProceedingJoinPoint pjp) {
    System.out.println("方法環繞start....around.");
    String result = null;
    try {
      result = (String) pjp.proceed();
    } catch (Throwable e) {
      e.printStackTrace();
    }
    System.out.println("方法環繞end.....around");  
    return result;
  }
  
  @After("within(com.example.controller.*Controller)")
  public void after(){
    System.out.println("方法之后執行....after.");
  }
  
  @AfterReturning("within(com.example.controller.*Controller)")
  public void afterReturning(){
    System.out.println("方法執行完執行.....afterReturning");  
  }
  
  @AfterThrowing("within(com.example.controller.*Controller)")
  public void afterThrowing(){
    System.out.println("異常出現之后.....afterThrowing");  
  }

}

啟動Spring Boot工程,訪問http://localhost:8080/hello?name=world ,控制臺輸出以下結果。

方法環繞start....around.
方法執行前執行.....before
hello  world
方法環繞end.....around
方法之后執行....after.
方法執行完執行.....afterReturning

本節通過一個例子,說明了如果基于@Aspect實現AOP編程,并在過程中體現了AOP概念中切面、切點、通知、連接點和目標對象。AOP的動態織入和AOP的代理將通過下文的兩節描述。分別是Java動態代理和cglib動態代理,前者是基于接口動態生成代理類,后者是通過子類生成動態代理類。

3. Java動態代理

代理模式是一種常用的Java設計模式,它的特征是代理類和委托類實現了同樣的接口,代理類負責預處理消息、過濾消息、把消息轉發給委托類,以及事后處理消息等。代理類并不實現真正的服務,而是調用委托類的方法來提供特定的服務。

所謂動態代理,就是在程序運行時,運用反射機制動態創建代理類。其實現主要通過java.lang.reflect.Proxy類和java.lang.reflect.InvocationHandler接口。其中,Proxy類主要用來獲取動態代理對象;InvocationHandler接口用來約束調用者實現。

要想使用Java動態代理,委托類、或者說是被代理的對象(target),必須是一個接口的實現類。

3.1 Java動態代理的使用

下面是Java動態代理的一個示例,說明見代碼中的注釋內容。

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Main {

  public static void main(String[] args) {
    // 實例化 target
    IHello hello = new Hello();
    // 實例化InvocationHandler
    DynamicProxyHandler handler = new DynamicProxyHandler(hello);
    // 通過Proxy類生成代理對象
    IHello proxy = (IHello) Proxy.newProxyInstance(hello.getClass().getClassLoader(),
        hello.getClass().getInterfaces(), handler);
    // 調用代理對象的方法
    proxy.sayHello("world");
  }
}


/**
 * JDK動態代理要實現 InvocationHandler 接口。
 */
class DynamicProxyHandler implements InvocationHandler {
  // 目標對象
  private Object target;

  /**
   * 構造方法
   * 
   * @param target 目標對象
   */
  public DynamicProxyHandler(Object target) {
    super();
    this.target = target;
  }

  /**
   * 執行目標對象target的方法
   */
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object result = null;
    try {
      System.out.println(method.getName() + " Method start .");
      result = method.invoke(target, args);
      System.out.println(method.getName() + " Method end .");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
  
  /** 
   * 獲取目標對象的代理對象 
   * @return 代理對象 
  public Object getProxy() {  
      return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),   
              target.getClass().getInterfaces(), this);  
  } 
  */  

}

/**
 * target實現的接口,用JDK動態代理生成的對象一定要實現一個接口
 */
interface IHello {
  // target method
  public void sayHello(String name);
}

/**
 * 被代理的target
 */
class Hello implements IHello {
  @Override
  public void sayHello(String name) {
    System.out.println("hello," + name);
  }

}

執行結果如下

sayHello Method start .
hello,world
sayHello Method end .

3.2 誰調用了invoke方法

DynamicProxyHandler中實現了InvocationHandler的invoke方法,表面上看不到是誰調用了。事實上,invok方法最終是由生成的動態代理類調用的,下面的代碼使用了sun.misc.ProxyGenerator把生成的動態代理類的字節碼寫到了磁盤上。通過反編譯生成的字節碼,我們就可以清晰地看到調用InvocationHandler的invoke方法的過程。

sun.misc.ProxyGenerator存在于JDK中,路徑是${JAVA_HOME}/jre/lib/rt.jar中; JRE中沒有這個類。如果你的工程里無法import該類,請修改JRE System Library到你的JDK目錄。

下面的代碼,把Hello.class的動態代理字節碼寫到了d:/logs/HelloProxy.class。

public class ProxyGeneratorUtils {
  
  public static void main(String[] args) {
    // 把Hello.class的動態代理類的字節碼保存到d:/logs/HelloProxy.class
    ProxyGeneratorUtils.writeProxyClassToHardDisk("d:/logs/HelloProxy.class");
  }
  
  
  /**
   * 把代理類的字節碼寫到磁盤
   * 
   * @param path 保存路徑
   */
  public static void writeProxyClassToHardDisk(String path) {
    // 獲取代理類的字節碼
    byte[] classFile = ProxyGenerator.generateProxyClass("HelloProxy",
             Hello.class.getInterfaces());
    FileOutputStream out = null;
    try {
      out = new FileOutputStream(path);
      out.write(classFile);
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

下面是HelloProxy.class的主要內容,可以看到生成的動態代理類HelloProxy和Hello一樣實現了IHello接口。HelloProxy繼承了Proxy類,Java不允許類多繼承,這也是“JDK動態代理時,委托類必須實現一個接口”的原因。

public final class HelloProxy extends Proxy implements IHello {

  private static Method m3;

  static {
    // 被調用的方法
     m3 = Class.forName("aop.IHello").getMethod("sayHello",
      new Class[] {Class.forName("java.lang.String")});
  }
  // 此處為上述實現的DynamicProxyHandler
  public HelloProxy(InvocationHandler paramInvocationHandler) {
    super(paramInvocationHandler);
  }
  //invoke方法就是在這里被調用的。
  public final void sayHello(String paramString) {
    try {
      this.h.invoke(this, m3, new Object[] {paramString});
      return;
    } catch (Error | RuntimeException localError) {
      throw localError;
    } catch (Throwable localThrowable) {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
}

3.3 InvocationHandler接口

InvocationHandler僅有一個方法,即invoke方法,它接受三個參數。proxy是代理類的實例;method是委托類被調用的方法;args是傳入method的參數。

 public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable;

3.4 Proxy類

Proxy類的使命就是為了獲取代理對象,在上面的例子中,我們就是使用它的newProxyInstance方法,獲取到了代理對象。其主要代碼如下。

/**
 *loader: 類加載器
 *interfaces:target實現的接口
 *h:InvocationHandler的實現類 
 */
public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,
   InvocationHandler h)throws IllegalArgumentException {

    //查找或者生成動態代理類。動態代理類的生成是在ProxyGenerator中實現的。
    Class<?> cl = getProxyClass0(loader, intfs);

    // 調用代理對象的構造方法
    final Constructor<?> cons = cl.getConstructor(constructorParams);
    // 把InvocationHandler實現類的實例傳遞到構造方法中
    final InvocationHandler ih = h;
    if (!Modifier.isPublic(cl.getModifiers())) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                cons.setAccessible(true);
                return null;
            }
        });
    }
    // 返回生成的代理類的實例。
    return cons.newInstance(new Object[]{h});
 }

4. cglib動態代理

JDK動態代理使用簡單,但存在著委托類必須實現一個或者多個接口;如果委托類沒有實現接口,而又要代理它,就可以使用CGLIB包。Spring AOP同時使用JDK動態代理和cglib;默認情況下,實現接口的類使用JDK動態代理;沒有實現接口的類,使用cglib。

cglib通過使用字節碼處理框架ASM(Java字節碼操控框架),來轉換字節碼并生成新的類;其原理是對指定的目標類生成一個子類,并覆蓋其中方法實現增強,但因為采用的是繼承,所以不能對final修飾的類進行代理。

下面是使用cglib的例子。

public class CglibMain {
  public static void main(String[] args) {
    // 實例化 target,沒有使用接口
    Hello hello = new Hello();
    // 實例化CglibProxy
    MyCglibProxy cglib = new MyCglibProxy();
    // 通過cglib獲取代理對象
    Hello proxy = (Hello) cglib.getInstance(hello);
    // 調用代理對象的方法
    proxy.sayHello("world");
  }
}


class MyCglibProxy implements MethodInterceptor {
  // 被代理的對象
  private Object target;

  /**
   * 創建代理對象
   */
  public Object getInstance(Object target) {
    this.target = target;
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(this.target.getClass());
    // 回調方法
    enhancer.setCallback(this);
    // 創建代理對象
    return enhancer.create();
  }

  @Override
  public Object intercept(Object obj, Method method,
      Object[] args, MethodProxy methodProxy) throws Throwable {
    System.out.println(method.getName() + " before-----------");
    // 生成的代理對象是委托類的子類,因此調用了super method
    Object result = methodProxy.invokeSuper(obj, args);
    System.out.println(method.getName() + " after-----------");
    return result;
  }

}

結果輸出如下。

sayHello before-----------
Hello, world
sayHello after-----------

5. 總結

以上是對Spring AOP的總結,我們記錄AOP的概念、應用場景,編寫了一個AOP的小例子,并分析了動態代理的生成過程。動態代理的生成過程對應Spring中源代碼分別是JdkDynamicAopProxy和CglibAopProxy,它們的package都是org.springframework.aop.framework,在spring-aop-*.jar中。

http://blog.csdn.net/moreevan/article/details/11977115
http://rejoy.iteye.com/blog/1627405
http://blog.csdn.net/xiaohai0504/article/details/6832990

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容