2010-12-14 63 views
2

Existe-t-il un moyen de dire à Java de suivre certaines fonctions en les marquant d'une annotation? Je veux être en mesure de le faire:Exécution de traçage avec des annotations

class Foo { 

    @trace 
    int foo(int bar) { 
     return bar + 5; 
    } 
} 

Ensuite, si le suivi est activé, je reçois:

** Entrée foo (5)

** foo retour: 10

Répondre

1

vous pouvez le faire en utilisant aop de printemps, avec des annotations @Around

Comment i AOP exploitation forestière m s'en œuvre:

ajouter à ce applicationContext.xml

<aop:aspectj-autoproxy/> 
    <context:annotation-config/> 
    <context:component-scan base-package="com.company.*"/> 

créer la classe suivante dans le paquet com.company *:.

package com.company.*; 

import org.apache.log4j.Logger; 
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.Around; 
import org.aspectj.lang.annotation.Aspect; 
import org.springframework.stereotype.Component; 
import org.springframework.util.StopWatch; 

@Component 
@Aspect 
public class AOPMethodLogger { 

    @Around("bean(*Service)") 
    public Object timeMethod(ProceedingJoinPoint joinPoint) throws Throwable { 
     StopWatch stopWatch = new StopWatch(); 
     stopWatch.start(); 
     Object retVal = joinPoint.proceed(); 
     stopWatch.stop(); 
     if(stopWatch.getTotalTimeMillis() > 35){ 
      StringBuffer logMessageStringBuffer = new StringBuffer(); 
      logMessageStringBuffer.append(joinPoint.getTarget().getClass().getName()); 
      logMessageStringBuffer.append("."); 
      logMessageStringBuffer.append(joinPoint.getSignature().getName()); 
      logMessageStringBuffer.append("("); 
      logMessageStringBuffer.append(joinPoint.getArgs()); 
      logMessageStringBuffer.append(")"); 
      logMessageStringBuffer.append(" execution time: "); 
      logMessageStringBuffer.append(stopWatch.getTotalTimeMillis()); 
      logMessageStringBuffer.append(" ms"); 
      System.out.println(logMessageStringBuffer.toString()); 
     } 
     return retVal; 
    } 

} 
1

Vous pouvez le faire sans avoir à ajouter des annotations par en utilisant un outil appelé InTrace.

REMARQUE: InTrace est un outil gratuit et open source que j'ai écrit.