0

I want to log time spent to log file when invoke some service methods , now I implement it by AOP, e.g.

@Around("execution(* sample..TaskService.*(..))")
public Object aroundStat(ProceedingJoinPoint joinPoint) throws Throwable {
    long start = System.currentTimeMillis();

    Object proceed = joinPoint.proceed();

    long end = System.currentTimeMillis();
    String methodName = joinPoint.getSignature().getName();
    log.info("{} taken time: {} ms",methodName,(end-start));
    return proceed;
}

but I want to know how could implement it by using Annotation just like @Trasactional, e.g.

@Service
@TimeLogging
public class TaskService {
    @TimeLogging
    List<TaskStatDTO> taskStatusStat(String name){
        //...
    }

    List<TaskStatDTO> finishedTaskStat(String name){
        //...
    }
    //...
}

Could I implement some class and override some method?

zhuguowei
  • 8,401
  • 16
  • 70
  • 106
  • Possible duplicate of [Spring AOP - pointcut for every method with an annotation](https://stackoverflow.com/questions/7817822/spring-aop-pointcut-for-every-method-with-an-annotation) – jny Jun 24 '17 at 13:07

1 Answers1

0
  1. don't use system time for measure time execution , use StopWatch from spring or apache. see good example - Measure execution time in Java – Spring StopWatch Example and spring api StopWatch
long start = System.currentTimeMillis();    
long end = System.currentTimeMillis();    
(end-start)

change to

StopWatch watch = new StopWatch();
watch.start();
..... execution
watch.stop();
watch.getTotalTimeMillis()
  1. instead of

@Around("execution(* sample..TaskService.*(..))")

use

@Around("execution(* sample..TaskService.(..) && @annotation( sample...TimeLogging)")

see Advice parameters

better : see Combining pointcut expressions and Sharing common pointcut definitions

@Pointcut("execution(@annotation(* sample...TimeLogging)")
private void withTimeExecutionLayer() {}

@Pointcut("execution(public *sample..service.* *(..))")
privatr void inServiceLayer() {}

@Pointcut("inServiceLayer() && withTimeExecutionLayer()")
private void auditTimeExecutionServiceLayer() {}
xyz
  • 5,228
  • 2
  • 26
  • 35
  • Thanks! but actually I want to know how to custom annotations just like `@Transactional`. If use spring aop it only could use at method level, if I want it , e.g. @TimeLogging on a class it does not support. – zhuguowei Jun 27 '17 at 01:23
  • so in this case if I should use `@within ` to implement it – zhuguowei Jun 28 '17 at 00:45