2012-02-29 16 views
9

Ho provato alcune nuove funzionalità di Spring e ho scoperto che le annotazioni @CachePut e @CacheEvict non hanno alcun effetto. Potrebbe essere che io faccia qualcosa di sbagliato. Potresti aiutarmi?Come dovrei usare le annotazioni @CachePut e @CacheEvict con ehCache (ehCache 2.4.4, Spring 3.1.1)

La mia applicazioneContext.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"/> 

Questa parte funziona bene.

Ma se voglio rimuovere un singolo valore dalla cache o sovrascriverlo non posso farlo. Cosa ho provato:

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

risposta

14

Ho trovato il motivo per cui non ha funzionato. Ho chiamato questo metodo da un altro metodo nella stessa classe. Quindi queste chiamate non hanno attraversato l'oggetto Proxy quindi le annotazioni non hanno funzionato.

Esempio corretto:

@Service 
@Transactional 
public class MyClass { 

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

e

@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

avuto lo stesso problema e questo riparato. Grazie! Ma qual è il problema specifico di avere "@CachePut" e "@Cachable" nella stessa classe? – DOUBL3P