Spring AOP的一點(diǎn)總結(jié)

1. Spring AOP介紹

AOP(Aspect-Oriented Programming),面向切面的編程,是OOP(面向?qū)ο蟮木幊蹋┑闹匾a(bǔ)充,所謂AOP,就是在執(zhí)行Java類中的方法前或后加入自定義方法。Spring AOP是Spring的一個(gè)重要組成部分,和IoC并稱為Spring的兩大基礎(chǔ)組件。關(guān)于Spring Ioc可以訪問http://www.itdecent.cn/p/6178ba063553。

spring-aop.png

1.1 小明搬磚的故事

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

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


1.2 AOP使用的場景

AOP用來封裝橫切關(guān)注點(diǎn),具體可以在下面的場景中使用。

  • Authentication 權(quán)限
  • Caching 緩存
  • Context passing 內(nèi)容傳遞
  • Error handling 錯(cuò)誤處理
  • Lazy loading 懶加載
  • Debugging  調(diào)試
  • logging,tracing,profiling and monitoring 記錄跟蹤 優(yōu)化 校準(zhǔn)
  • Performance optimization 性能優(yōu)化
  • Persistence  持久化
  • Resource pooling 資源池
  • Synchronization 同步
  • Transactions 事務(wù)

1.3 AOP的相關(guān)概念

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

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

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

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

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

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

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

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

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

2. 基于@Aspect的AOP編程實(shí)踐

本節(jié)通過一個(gè)簡單的例子,說明如何實(shí)現(xiàn)基于@Aspect的AOP編程實(shí)踐。我們將在Controller執(zhí)行方法的前后,輸出一些日志。

2.1 pom.xml中引入AOP

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

2.2 HelloController

這個(gè)Controller就是我們選定的目標(biāo)對象(Target Object),它的hello()方法就是連接點(diǎn)(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 // 該注解標(biāo)示該類為切面類,切面是由通知和切點(diǎn)組成的。
public class ApiAspect {
  
  //雙引號中間的內(nèi)容是PointCut(切點(diǎn))表達(dá)式。@Before是前屬通知
  @Before("execution(* com.example.controller.HelloController.*(..))")  
  public void before(){
    System.out.println("方法執(zhí)行前執(zhí)行.....before");  
  }

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

}

啟動(dòng)Spring Boot工程,訪問http://localhost:8080/hello?name=world ,控制臺(tái)輸出以下結(jié)果。

方法環(huán)繞start....around.
方法執(zhí)行前執(zhí)行.....before
hello  world
方法環(huán)繞end.....around
方法之后執(zhí)行....after.
方法執(zhí)行完執(zhí)行.....afterReturning

本節(jié)通過一個(gè)例子,說明了如果基于@Aspect實(shí)現(xiàn)AOP編程,并在過程中體現(xiàn)了AOP概念中切面、切點(diǎn)、通知、連接點(diǎn)和目標(biāo)對象。AOP的動(dòng)態(tài)織入和AOP的代理將通過下文的兩節(jié)描述。分別是Java動(dòng)態(tài)代理和cglib動(dòng)態(tài)代理,前者是基于接口動(dòng)態(tài)生成代理類,后者是通過子類生成動(dòng)態(tài)代理類。

3. Java動(dòng)態(tài)代理

代理模式是一種常用的Java設(shè)計(jì)模式,它的特征是代理類和委托類實(shí)現(xiàn)了同樣的接口,代理類負(fù)責(zé)預(yù)處理消息、過濾消息、把消息轉(zhuǎn)發(fā)給委托類,以及事后處理消息等。代理類并不實(shí)現(xiàn)真正的服務(wù),而是調(diào)用委托類的方法來提供特定的服務(wù)。

所謂動(dòng)態(tài)代理,就是在程序運(yùn)行時(shí),運(yùn)用反射機(jī)制動(dòng)態(tài)創(chuàng)建代理類。其實(shí)現(xiàn)主要通過java.lang.reflect.Proxy類和java.lang.reflect.InvocationHandler接口。其中,Proxy類主要用來獲取動(dòng)態(tài)代理對象;InvocationHandler接口用來約束調(diào)用者實(shí)現(xiàn)。

要想使用Java動(dòng)態(tài)代理,委托類、或者說是被代理的對象(target),必須是一個(gè)接口的實(shí)現(xiàn)類。

3.1 Java動(dòng)態(tài)代理的使用

下面是Java動(dòng)態(tài)代理的一個(gè)示例,說明見代碼中的注釋內(nèi)容。

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

public class Main {

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


/**
 * JDK動(dòng)態(tài)代理要實(shí)現(xiàn) InvocationHandler 接口。
 */
class DynamicProxyHandler implements InvocationHandler {
  // 目標(biāo)對象
  private Object target;

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

  /**
   * 執(zhí)行目標(biāo)對象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;
  }
  
  /** 
   * 獲取目標(biāo)對象的代理對象 
   * @return 代理對象 
  public Object getProxy() {  
      return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),   
              target.getClass().getInterfaces(), this);  
  } 
  */  

}

/**
 * target實(shí)現(xiàn)的接口,用JDK動(dòng)態(tài)代理生成的對象一定要實(shí)現(xiàn)一個(gè)接口
 */
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);
  }

}

執(zhí)行結(jié)果如下

sayHello Method start .
hello,world
sayHello Method end .

3.2 誰調(diào)用了invoke方法

DynamicProxyHandler中實(shí)現(xiàn)了InvocationHandler的invoke方法,表面上看不到是誰調(diào)用了。事實(shí)上,invok方法最終是由生成的動(dòng)態(tài)代理類調(diào)用的,下面的代碼使用了sun.misc.ProxyGenerator把生成的動(dòng)態(tài)代理類的字節(jié)碼寫到了磁盤上。通過反編譯生成的字節(jié)碼,我們就可以清晰地看到調(diào)用InvocationHandler的invoke方法的過程。

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

下面的代碼,把Hello.class的動(dòng)態(tài)代理字節(jié)碼寫到了d:/logs/HelloProxy.class。

public class ProxyGeneratorUtils {
  
  public static void main(String[] args) {
    // 把Hello.class的動(dòng)態(tài)代理類的字節(jié)碼保存到d:/logs/HelloProxy.class
    ProxyGeneratorUtils.writeProxyClassToHardDisk("d:/logs/HelloProxy.class");
  }
  
  
  /**
   * 把代理類的字節(jié)碼寫到磁盤
   * 
   * @param path 保存路徑
   */
  public static void writeProxyClassToHardDisk(String path) {
    // 獲取代理類的字節(jié)碼
    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的主要內(nèi)容,可以看到生成的動(dòng)態(tài)代理類HelloProxy和Hello一樣實(shí)現(xiàn)了IHello接口。HelloProxy繼承了Proxy類,Java不允許類多繼承,這也是“JDK動(dòng)態(tài)代理時(shí),委托類必須實(shí)現(xiàn)一個(gè)接口”的原因。

public final class HelloProxy extends Proxy implements IHello {

  private static Method m3;

  static {
    // 被調(diào)用的方法
     m3 = Class.forName("aop.IHello").getMethod("sayHello",
      new Class[] {Class.forName("java.lang.String")});
  }
  // 此處為上述實(shí)現(xiàn)的DynamicProxyHandler
  public HelloProxy(InvocationHandler paramInvocationHandler) {
    super(paramInvocationHandler);
  }
  //invoke方法就是在這里被調(diào)用的。
  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僅有一個(gè)方法,即invoke方法,它接受三個(gè)參數(shù)。proxy是代理類的實(shí)例;method是委托類被調(diào)用的方法;args是傳入method的參數(shù)。

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

3.4 Proxy類

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

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

    //查找或者生成動(dòng)態(tài)代理類。動(dòng)態(tài)代理類的生成是在ProxyGenerator中實(shí)現(xiàn)的。
    Class<?> cl = getProxyClass0(loader, intfs);

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

4. cglib動(dòng)態(tài)代理

JDK動(dòng)態(tài)代理使用簡單,但存在著委托類必須實(shí)現(xiàn)一個(gè)或者多個(gè)接口;如果委托類沒有實(shí)現(xiàn)接口,而又要代理它,就可以使用CGLIB包。Spring AOP同時(shí)使用JDK動(dòng)態(tài)代理和cglib;默認(rèn)情況下,實(shí)現(xiàn)接口的類使用JDK動(dòng)態(tài)代理;沒有實(shí)現(xiàn)接口的類,使用cglib。

cglib通過使用字節(jié)碼處理框架ASM(Java字節(jié)碼操控框架),來轉(zhuǎn)換字節(jié)碼并生成新的類;其原理是對指定的目標(biāo)類生成一個(gè)子類,并覆蓋其中方法實(shí)現(xiàn)增強(qiáng),但因?yàn)椴捎玫氖抢^承,所以不能對final修飾的類進(jìn)行代理。

下面是使用cglib的例子。

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


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

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

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

}

結(jié)果輸出如下。

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

5. 總結(jié)

以上是對Spring AOP的總結(jié),我們記錄AOP的概念、應(yīng)用場景,編寫了一個(gè)AOP的小例子,并分析了動(dòng)態(tài)代理的生成過程。動(dòng)態(tài)代理的生成過程對應(yīng)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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容