Question

This is my code snippet:

@Around("execution(* de.my.package.path.controller.RecommendationController.recommendItems*(..))")
    public Object measureTimeWithOverhead(ProceedingJoinPoint joinPoint) throws Throwable {
        long startNanoTime = System.nanoTime();
        Object proceed = joinPoint.proceed();
        long endNanoTime = System.nanoTime();
        long diff = endNanoTime - startNanoTime;
        System.out.println("Elapsed time: " + (diff));
        return proceed;
    }

I want to use the value of the "diff" variable in my further program. How can I retrieve this value? Is this even possible at all?

(btw, I am working on a Spring 4.0.2 MVC application)

Was it helpful?

Solution

Currently, no. The diff variable is a local variable and is therefore only accessible within the body of the method, after it's been declared (and initialized).

AOP advice is meant to add additional behavior (by executing code) at a certain point in the execution of a program. It's a self contained component. It can know about the code it's intercepting, but not vice-versa.

There are obviously work arounds if you need to do this, but I don't recommend it. You can use a static ThreadLocal in some class and set its value to whatever diff is. You can then access that ThreadLocal anywhere else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top