سؤال

Is there a way to add a logger instance with Spring ? And is there a way to trace each method calls in my custom code ?

I usually do this :

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...
  }
}

Is there a way to simplify this with Spring ?

Goal is :

  • avoid repeatitive code
هل كانت مفيدة؟

المحلول

<?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>

This help me to get trace on each calls of all methods of all classes in fr.my.package.dao package.

Thanks to @m-deinum

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top