Differences between revisions 1 and 2
Deletions are marked like this. | Additions are marked like this. |
Line 55: | Line 55: |
System.out.println(""); System.out.println("" + greeting.getClass()); System.out.println("" + greeting.getClass().getClassLoader()); System.out.println("" + Sample.class.getClassLoader()); |
|
Line 63: | Line 68: |
class aop.Sample$Greeting$$EnhancerByGuice$$c979486 sun.misc.Launcher$AppClassLoader@a90653 sun.misc.Launcher$AppClassLoader@a90653 |
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(); System.out.println(""); System.out.println("" + greeting.getClass()); System.out.println("" + greeting.getClass().getClassLoader()); System.out.println("" + Sample.class.getClassLoader()); } }
実行結果は以下
before hello, world after class aop.Sample$Greeting$$EnhancerByGuice$$c979486 sun.misc.Launcher$AppClassLoader@a90653 sun.misc.Launcher$AppClassLoader@a90653