Google Guice - AOP




AOP,面向切面程式設計,它將程式邏輯分解成不同的部分,稱為“關注點”。跨越應用程式多個點的功能稱為橫切關注點,這些橫切關注點在概念上與應用程式的業務邏輯是分開的。一些常見的方面示例包括日誌記錄、審計、宣告式事務、安全、快取等。

OOP 中模組化的關鍵單元是類,而在 AOP 中,模組化的單元是方面。依賴注入幫助你解耦應用程式物件,而 AOP 幫助你解耦橫切關注點與其影響的物件。AOP 就像 Perl、.NET、Java 等程式語言中的觸發器。Guice 提供攔截器來攔截應用程式。例如,當執行方法時,你可以在方法執行之前或之後新增額外功能。

重要類

  • Matcher - Matcher 是一個介面,用於接受或拒絕值。在 Guice AOP 中,我們需要兩個匹配器:一個用於定義參與的類,另一個用於這些類的特定方法。

  • MethodInterceptor - 當呼叫匹配的方法時,將執行 MethodInterceptor。它們可以檢查呼叫:方法、引數和接收例項。我們可以執行橫切邏輯,然後委託給底層方法。最後,我們可以檢查返回值或異常並返回。

示例

建立一個名為 GuiceTester 的 Java 類。

GuiceTester.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck(); 
   } 
}

class TextEditor {
   private SpellChecker spellChecker;

   @Inject
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }

   public void makeSpellCheck(){
      spellChecker.checkSpelling();
   }
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() {
      bind(SpellChecker.class).to(SpellCheckerImpl.class);
      bindInterceptor(Matchers.any(), 
         Matchers.annotatedWith(CallTracker.class), 
         new CallTrackerService());
   } 
}

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}

//spell checker implementation
class SpellCheckerImpl implements SpellChecker {

   @Override @CallTracker
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
@interface CallTracker {}

class CallTrackerService implements MethodInterceptor  {

   @Override
   public Object invoke(MethodInvocation invocation) throws Throwable {
      System.out.println("Before " + invocation.getMethod().getName());
      Object result = invocation.proceed();
      System.out.println("After " + invocation.getMethod().getName());
      return result;
   }
}

輸出

編譯並執行檔案,你可能會看到以下輸出。

Before checkSpelling
Inside checkSpelling.
After checkSpelling
廣告
© . All rights reserved.