JSF2とCDIでAOP(Interceptor)
■JSF2(Mojarra)で管理ビーンをCDIにしている時にAOP(Interceptor)してみたヽ(=´▽`=)ノ
まずはアノテーション。良く分からないのでオマジナイとして名前(MyInterceptorLog)以外全コピーw
import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.interceptor.InterceptorBinding; @Inherited @InterceptorBinding @Target({TYPE, METHOD}) @Retention(RUNTIME) public @interface MyInterceptorLog { }
次にインターセプターの実装クラス。
SerializableしているのはSessionScopedで使うため。
import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; @MyInterceptorLog @Interceptor public class LoggingInterceptor implements Serializable { private static final Logger LOG = Logger.getLogger(YamchaLoggingInterceptor.class.getName()); @AroundInvoke public Object methodLog(InvocationContext ic) throws Exception { LOG.log(Level.INFO, "[start]" + ic.getTarget().getClass().getSimpleName()+ "#" + ic.getMethod().getName()); try { return ic.proceed(); } finally { LOG.log(Level.INFO, "[end ]" + ic.getTarget().getClass().getSimpleName() + "#" + ic.getMethod().getName()); } } }
beans.xmlにインターセプタークラス「<interceptors>」の登録
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"> <interceptors> <class>packege.LoggingInterceptor</class> </interceptors> </beans>
管理ビーンにアノテーションを追加
import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import packege.MyInterceptorLog; @SessionScoped @MyInterceptorLog @Named(value="b01") public class B01 implements Serializable{ }
実行結果
情報: [start]B01$Proxy$_$$_WeldSubclass#getUserId 情報: [end ]B01$Proxy$_$$_WeldSubclass#getUserId 情報: [start]B01$Proxy$_$$_WeldSubclass#getUserPw 情報: [end ]B01$Proxy$_$$_WeldSubclass#getUserPw 情報: [start]B01$Proxy$_$$_WeldSubclass#setUserId 情報: [end ]B01$Proxy$_$$_WeldSubclass#setUserId 情報: [start]B01$Proxy$_$$_WeldSubclass#setUserPw 情報: [end ]B01$Proxy$_$$_WeldSubclass#setUserPw 情報: [start]B01$Proxy$_$$_WeldSubclass#aaa 情報: [end ]B01$Proxy$_$$_WeldSubclass#aaa 情報: [start]B01$Proxy$_$$_WeldSubclass#getUserId 情報: [end ]B01$Proxy$_$$_WeldSubclass#getUserId 情報: [start]B01$Proxy$_$$_WeldSubclass#getUserPw 情報: [end ]B01$Proxy$_$$_WeldSubclass#getUserPw
実際のJSFからのメソッドは「aaa」しか呼んでなく、要らないgetter/setterも出ているけど、ちゃんと出たーワーイ!!\(o ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄▽ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄o)/ワーイ!!