2014-04-07 24 views
0

有沒有辦法給Spring添加記錄器實例? 有沒有辦法跟蹤我的自定義代碼中的每個方法調用?添加記錄器與春天

我經常這樣做:

package my.java.code; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
public class A { 
    // How to add this line with Spring ? 
    private static final Logger logger = LoggerFactory.getLogger(A.class); 
    public void A() { 
    // How to add this line with Spring ? 
    logger.trace(""); 
    // Do something... 
    } 
    public void A(Object o) { 
    // How to add this line with Spring ? 
    logger.trace("{}", o); 
    // Do something... 
    } 
    public void method1() { 
    // How to add this line with Spring ? 
    logger.trace(""); 
    // Do something... 
    } 
    public void method2(Object o) { 
    // How to add this line with Spring ? 
    logger.trace("{}", o); 
    // Do something... 
    } 
} 

有沒有辦法用Spring來簡化這個?

目標是:

  • 避免repeatitive代碼
+0

我不明白的問題。你有什麼問題? –

+1

你想擺脫重複的代碼? – geoand

+2

使用Spring AOP和['CustomizableTraceInterceptor'](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/aop/interceptor/CustomizableTraceInterceptor.html)。另請參閱http://stackoverflow.com/questions/13182205/java-spring-aop-using-customizabletraceinterceptor-with-javaconfig-enableaspec –

回答

1
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop.xsd"> 

    <bean id="customizableTraceInterceptor" 
    class="org.springframework.aop.interceptor.CustomizableTraceInterceptor"> 
    <property name="enterMessage" 
     value="Entering $[targetClassName].$[methodName]($[argumentTypes] $[arguments])" /> 
    <property name="exitMessage" value="Leaving $[methodName](): $[returnValue]" /> 
    </bean> 

    <aop:config> 
    <aop:advisor advice-ref="customizableTraceInterceptor" 
     pointcut="execution(* fr.my.package.dao..*.*(..))" /> 
    </aop:config> 

</beans> 

這幫助我得到的fr.my.package.dao包中的所有類的所有方法調用每一個痕跡。

感謝@ M-deinum