简体   繁体   English

我应该如何在ehCache中使用@CachePut和@CacheEvict注释(ehCache 2.4.4,Spring 3.1.1)

[英]How should I use @CachePut and @CacheEvict annotations with ehCache (ehCache 2.4.4, Spring 3.1.1)

I tried some new Spring features and I found out that @CachePut and @CacheEvict annotations has no effect. 我尝试了一些新的Spring功能,我发现@CachePut和@CacheEvict注释没有任何效果。 May be I do something wrong. 可能是我做错了什么。 Could you help me? 你可以帮帮我吗?

My applicationContext.xml. 我的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"/>

This part works well. 这部分效果很好。

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

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

But if I want remove single value from cache or override it I can't do that. 但是,如果我想从缓存中删除单个值或覆盖它,我不能这样做。 What I tested: 我测试了什么:

@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;
}

I found the reason why it didn't work. 我找到了它无效的原因。 I called this methods from other method in the same class. 我在同一个类中使用其他方法调用此方法。 So this calls didn't get through Proxy object therefore the annotations didn't work. 所以这个调用没有通过Proxy对象,因此注释不起作用。

Correct example: 正确的例子:

@Service
@Transactional
public class MyClass {

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

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM