Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[aspectj-users] Aspect instance per annotated method


Hello all,

I have a simple aspect for caching the result of a method call.

An annotation is used to mark a method which should be cached:

    public @interface CacheResult { }

The aspect is implemented like this:

    @Aspect("perthis(targetMethod())")
    public class CacheResultAspect {

        private Object result;

        @Pointcut("execution(@CacheResult * *.*())")
        public void targetMethod() { }

        @Around("targetMethod()")
public Object aroundMethod(ProceedingJoinPoint thisJoinPoint) throws Throwable {
            if (result == null) {
                result = thisJoinPoint.proceed();
            }
            return result;
        }
    }

This works great for target classes with only one @CacheResult method.

But the problem is target classes which have multiple different @CacheResult methods:

    class Target {
        @CacheResult String method1() { return "method1"; }
        @CacheResult String method2() { return "method2"; }
    }

    Target target = new Target();
    target.method1();   // Caches and returns "method1"
target.method2(); // Returns cached "method1" but should separately cache and return "method2"

Currently, one instance of CacheResultAspect is created for each instance of a target class, so the cache result is (incorrectly) shared across all the @CacheResult methods of the target object.

Is there a way to make AspectJ create a separate instance of CacheResultAspect for each @CacheResult method in a target object?

I could use a Map to work around this, but perhaps there is a better or more performant solution?

Thanks,
Jon.




Back to the top