Springに付属のAOPサンプルのログトレースを動かすには? | Java Springの逆引きメモ

Java Springの逆引きメモ

JavaのSpring frameworkのメモを書いていきます!
初心者の勉強ノートなので間違いがあるかもしれませんが、何かヒントになることがあれば幸いです。

Springにはすぐに使用できるAOP用のクラスが用意されています。

そのうちのひとつであるトレースログをするクラスを見てみましょう。

AOPのおおよその設定方法が分かっていれば簡単です。




【Spring設定ファイルの設定例】

Springの設定ファイルに以下の記述を追加します。


<bean id="debugInterceptor" class="org.springframework.aop.interceptor.DebugInterceptor"/>

<aop:config>
<aop:advisor pointcut="execution(* loadUserByUsername(..))" advice-ref="debugInterceptor" />
</aop:config>


【Log4jの設定ファイルの設定例】

log4j.logger.org.springframework.aop.interceptor.DebugInterceptor=DEBUG, stdout
log4j.additivity.org.springframework.aop.interceptor.DebugInterceptor=false




【説明】

実装自体は既にSpringがしてくれているので、設定ファイルに記述するだけです。

Springが用意しているトレースログ用のクラスは以下の名前です。

org.springframework.aop.interceptor.DebugInterceptor

ただし、用意されたクラスはログのレベルがDEBUGでないと動作しません。

そこで、Log4jにも設定が必要です。



<Springの設定ファイルについて>

DIの基本的な設定ファイルは、以下を参照してください。

・DIの設定ファイルを書くには?


あとは、AOPの普通の設定どおりに設定するだけです。

上記の例では、メソッド名がloadUserByUsernameのものすべてに織り込んでいます。

分からない方は、以下を参照してください。

・DIxAOPの機能について



<Log4jの設定ファイルについて>

これも、普通のLog4jの設定どおりです。

分からない方は以下を参照してください。

・実行したSQL文のログを出力するには?  (説明のところでLog4jの説明もしています)




【出力例】

2009-04-05 14:45:52,015 [http-8080-Processor24] DEBUG org.springframework.aop.interceptor.DebugInterceptor - Entering ReflectiveMethodInvocation: public abstract org.springframework.security.userdetails.UserDetails org.springframework.security.userdetails.UserDetailsService.loadUserByUsername(java.lang.String) throws org.springframework.security.userdetails.UsernameNotFoundException,org.springframework.dao.DataAccessException; target is of class [org.springframework.security.userdetails.memory.InMemoryDaoImpl]; count=1
2009-04-05 14:45:52,015 [http-8080-Processor24] DEBUG org.springframework.aop.interceptor.DebugInterceptor - Exiting ReflectiveMethodInvocation: public abstract org.springframework.security.userdetails.UserDetails org.springframework.security.userdetails.UserDetailsService.loadUserByUsername(java.lang.String) throws org.springframework.security.userdetails.UsernameNotFoundException,org.springframework.dao.DataAccessException; target is of class [org.springframework.security.userdetails.memory.InMemoryDaoImpl]; count=1



どうです?

うまく行きましたか?



参考:

・DIxAOPの機能について

・実行したSQL文のログを出力するには?

SpringによるAOPの導入