2012-02-29 17 views
9

Probé algunas características nuevas de Spring y descubrí que las anotaciones @CachePut y @CacheEvict no tienen ningún efecto. Puede ser que haga algo mal. ¿Usted me podría ayudar?¿Cómo debo usar las anotaciones @CachePut y @CacheEvict con ehCache (ehCache 2.4.4, Spring 3.1.1)

Mi 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"/> 

Esta pieza funciona bien.

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

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

Pero si quiero eliminar el único valor de la memoria caché o anularlo no puedo hacer eso. Lo que probé:

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

Respuesta

14

Encontré la razón por la que no funcionó. Llamé a este método desde otro método en la misma clase. Entonces, estas llamadas no se transmitieron a través del objeto Proxy, por lo tanto, las anotaciones no funcionaron.

Ejemplo correcto:

@Service 
@Transactional 
public class MyClass { 

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

y

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

tenía el mismo problema y esto lo arregló. ¡Gracias! ¿Pero cuál es el problema específico de tener '@CachePut' y '@Cachable' en la misma Clase? – DOUBL3P