how to prevent a return value from cache to be changed in spring cacheable

后端 未结 3 682
执念已碎
执念已碎 2021-01-03 12:24

i\'m working around spring 3.1 annotation cache with ehcache as a cache implement.

a method with return value like this

@Cacheable(\"cache\")
public          


        
3条回答
  •  死守一世寂寞
    2021-01-03 12:58

    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:

    
    

提交回复
热议问题