AOPの使い方
簡単なサンプル
import java.lang.annotation.*; import org.aopalliance.intercept.*; import com.google.inject.*; import com.google.inject.matcher.*; public class Sample { /** インターセプトするメソッドの目印となるアノテーション */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface DebugTrace {} /** インターセプト対象のメソッドを持つクラス */ public static class Greeting { @DebugTrace public void hello() { System.out.println("hello, world"); } } /** インターセプタ定義 */ public static class DebugTracer implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("before "); Object r = invocation.proceed(); System.out.println("after"); return r; } } /** テスト */ public static void main(String[]args) { Injector injector = Guice.createInjector( new AbstractModule() { protected void configure() { bindInterceptor( Matchers.any(), Matchers.annotatedWith(DebugTrace.class), new DebugTracer() ); } } ); Greeting greeting = injector.getInstance(Greeting.class); greeting.hello(); } }
実行結果は以下
before hello, world after