【问题标题】:How should I use @CachePut and @CacheEvict annotations with ehCache (ehCache 2.4.4, Spring 3.1.1)我应该如何将 @CachePut 和 @CacheEvict 注释与 ehCache 一起使用(ehCache 2.4.4,Spring 3.1.1)
【发布时间】:2012-03-19 00:35:35
【问题描述】:

我尝试了一些新的 Spring 特性,发现 @CachePut 和 @CacheEvict 注解没有效果。可能是我做错了什么。你能帮帮我吗?

我的 applicationContext.xml。

<cache:annotation-driven />

<!--also tried this-->
<!--<ehcache:annotation-driven />-->

<bean id="cacheManager" 
        class="org.springframework.cache.ehcache.EhCacheCacheManager"
        p:cache-manager-ref="ehcache"/>
<bean id="ehcache"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
        p:config-location="classpath:ehcache.xml"/>

这部分效果很好。

@Cacheable(value = "finders")
public Finder getFinder(String code)
{
    return getFinderFromDB(code);
}

@CacheEvict(value = "finders", allEntries = true)
public void clearCache()
{
}

但如果我想从缓存中删除单个值或覆盖它,我不能这样做。我测试了什么:

@CacheEvict(value = "finders", key = "#finder.code")
public boolean updateFinder(Finder finder, boolean nullValuesAllowed)
{
    // ...
}

/////////////

@CacheEvict(value = "finders")
public void clearCache(String code)
{
}

/////////////

@CachePut(value = "finders", key = "#finder.code")
public Finder updateFinder(Finder finder, boolean nullValuesAllowed)
{
    // gets newFinder that is different
    return newFinder;
}

【问题讨论】:

    标签: spring ehcache


    【解决方案1】:

    我找到了它不起作用的原因。我从同一个类中的其他方法调用了这个方法。所以这个调用没有通过 Proxy 对象,因此注释不起作用。

    正确示例:

    @Service
    @Transactional
    public class MyClass {
    
        @CachePut(value = "finders", key = "#finder.code")
        public Finder updateFinder(Finder finder, boolean nullValuesAllowed)
        {
            // gets newFinder
            return newFinder;
        }
    }
    

    @Component
    public class SomeOtherClass {
    
        @Autowired
        private MyClass myClass;
    
        public void updateFinderTest() {
            Finder finderWithNewName = new Finder();
            finderWithNewName.setCode("abc");
            finderWithNewName.setName("123");
            myClass.updateFinder(finderWithNewName, false);
        }
    }
    

    【讨论】:

    • 有同样的问题,这解决了它。谢谢!但是在同一个类中拥有“@CachePut”和“@Cachable”的具体问题是什么?
    • @DOUBL3P 没有问题,除了注释通过隐藏的代理对象工作,从类继承。如果您直接调用方法(绕过代理),您将无法获得代理功能。但是您可能会从 applicationContext (getBean) 中获取由代理包装的 bean。然后,它会起作用。
    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 2011-01-26
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 2014-02-09
    相关资源
    最近更新 更多