Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

spring

ehcache

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;
}
like image 843
Gosha U. Avatar asked Feb 29 '12 14:02

Gosha U.


1 Answers

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);
    }
}
like image 171
Gosha U. Avatar answered Oct 03 '22 05:10

Gosha U.