You could write your own aspect that always creates a copy of the returned value, which would make you independent of some Ehcache settings.
At first, a marker annotation like @CopyReturnValue
would be nice for expressing the pointcut:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CopyReturnValue {
}
Now, the aspect can use this annotation for the pointcut expression:
@Aspect
@Component
public class CopyReturnValueAspect {
@Around("@annotation(CopyReturnValue)")
public Object doCopyReturnValue(ProceedingJoinPoint pjp) throws Throwable {
Object retVal = pjp.proceed();
Object copy = BeanUtils.cloneBean(retVal); // create a copy in some way
return copy;
}
}
Finally, add the annotation to your method:
@CopyReturnValue
@Cacheable("cache")
public MyObject getObj(Object param);
For the CopyReturnValueAspect
I use BeanUtils
to create a copy of the returned value - just as an example. For further information on that topic, you might want to look at How to copy properties from one Java bean to another?
Oh, don't forget to enable @AspectJ support in you Spring configuration if you haven't already:
<aop:aspectj-autoproxy />