Guiceを使ってみる - インターセプタの適用
Guiceから取得するインスタンスにインターセプタを適用します。これもModuleで明示します。
サービスと実装:
/** * サービスのインターフェイス */ static interface Kitten { void meow (); } /** * サービスの実装 */ static class KittenImpl implements Kitten { public void meow () { System.out.println( "meow!" ); } }
サンプル:
Injector injector = Guice.createInjector( new Module() { public void configure ( Binder b ) { b.bind( Kitten.class ).to( KittenImpl.class ); // アスペクトの設定。 b.bindInterceptor( Matchers.any(), // すべてのクラスの Matchers.any(), // すべてのメソッドに new MethodInterceptor() { public Object invoke ( MethodInvocation m ) throws Throwable { try { System.out.println( "meow?" ); return m.proceed(); } finally { System.out.println( "meow!!" ); } } } ); } }); Kitten s = injector.getInstance(Kitten.class); s.meow(); s.hashCode();
出力:
meow? meow! meow!! meow? meow!!