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

Gosha U. picture Gosha U. · Feb 29, 2012 · Viewed 20k times · Source

I tried some new Spring features and I found out that @CachePut and @CacheEvict annotations has no effect. May be I do something wrong. Could you help me?

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

Answer

Gosha U. picture Gosha U. · Mar 1, 2012

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.

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