Guice-aop

提供:Dev Guides
移動先:案内検索

Google Guice-AOP

AOP、アスペクト指向プログラミングは、プログラムロジックをいわゆる懸念と呼ばれる別個の部分に分解することを伴います。 アプリケーションの複数のポイントにまたがる機能は横断的関心事と呼ばれ、これらの横断的関心事はアプリケーションのビジネスロジックと概念的に分離されています。 ロギング、監査、宣言的トランザクション、セキュリティ、キャッシングなどの側面のさまざまな一般的な良い例があります。

OOPのモジュール性の重要な単位はクラスですが、AOPのモジュール性の単位は側面です。 依存性注入は、アプリケーションオブジェクトを相互に分離するのに役立ち、AOPは、影響を受けるオブジェクトから横断的な関心事を分離するのに役立ちます。 AOPは、Perl、.NET、Javaなどのプログラミング言語のトリガーのようなものです。 Guiceは、アプリケーションをインターセプトするインターセプターを提供します。 たとえば、メソッドの実行時に、メソッドの実行前または実行後に機能を追加できます。

重要なクラス

  • Matcher -Matcherは、値を受け入れるか拒否するかのインターフェイスです。 Guice AOPでは、2つのマッチャーが必要です。1つは参加するクラスを定義するものであり、もう1つはそれらのクラスのメソッド用です。
  • MethodInterceptor -MethodInterceptorsは、一致するメソッドが呼び出されたときに実行されます。 メソッド、引数、受信インスタンスなどの呼び出しを検査できます。 クロスカットロジックを実行してから、基になるメソッドに委任できます。 最後に、戻り値または例外を調べて戻ります。

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