如何防止缓存中的返回值在spring cacheable中更改 [英] how to prevent a return value from cache to be changed in spring cacheable

查看:269
本文介绍了如何防止缓存中的返回值在spring cacheable中更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ehcache作为缓存工具来处理spring 3.1注释缓存。

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 MyObject getObj(Object param);

我第一次得到myobject返回值,并且它是可编辑的。
ehcache可以通过设置copyOnRead或copyOnWrite来做些什么。
它会在读/写时强制序列化对象。
但是第一次spring不会从缓存中获取值,它总是按方法本身返回。

i got a myobject return value for the first time,and it's editable. ehcache can do something for that by setting "copyOnRead" or "copyOnWrite". it will force serialize object on read/write. but at the first time spring will not get value from cache,it always return by method itself.

是否有某种方法可以获得只读返回值?

is there some way to get a readonly return value?

推荐答案

您可以编写自己的方面,始终创建返回值的副本,这将使您独立于某些Ehcache设置。

You could write your own aspect that always creates a copy of the returned value, which would make you independent of some Ehcache settings.

首先,像 @CopyReturnValue 这样的标记注释会很好地表达切入点:

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);

对于 CopyReturnValueAspect 我使用 BeanUtils 创建返回值的副本 - 仅作为示例。有关该主题的更多信息,您可能需要查看如何将属性从一个Java bean复制到另一个?

哦,不要忘记在你的Spring配置中启用@AspectJ支持已经:

Oh, don't forget to enable @AspectJ support in you Spring configuration if you haven't already:

<aop:aspectj-autoproxy />

这篇关于如何防止缓存中的返回值在spring cacheable中更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆