2012-02-29 24 views
9

Próbowałem nowych funkcji Spring i odkryłem, że adnotacje @CachePut i @CacheEvict nie mają żadnego efektu. Może być coś złego. Czy mógłbyś mi pomóc?Jak używać adnotacji @CachePut i @CacheEvict przy użyciu ehCache (ehCache 2.4.4, Spring 3.1.1)

Moja aplikacjaContext.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"/> 

Ta część działa dobrze.

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

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

Ale jeśli chcę usunąć pojedynczą wartość z pamięci podręcznej lub nadpisać ją, nie mogę tego zrobić. Co przetestowałem:

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

Odpowiedz

14

Znalazłem powód, dla którego to nie zadziałało. Wywołałem tę metodę z innej metody w tej samej klasie. Tak więc te połączenia nie przeszły przez obiekt Proxy, dlatego adnotacje nie działały.

Prawidłowe przykład:

@Service 
@Transactional 
public class MyClass { 

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

i

@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

miał ten sam problem i to naprawił. Dzięki! Ale jaki jest konkretny problem związany z "@CachePut" i "@Cachable" w tej samej klasie? – DOUBL3P

Powiązane problemy