2012-02-29 4 views
9

新しいSpringの機能を試してみましたが、@CachePutと@CacheEvictアノテーションは効果がありません。私は何か間違っているかもしれません。私たちを手伝ってくれますか?eHCacheで@CachePutと@CacheEvictアノテーションを使用する方法(ehCache 2.4.4、Spring 3.1.1)

私の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"/> 

この部分はうまくいきます。

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

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

しかし、私はそれをキャッシュから単一の値を削除したり、上書きしたい場合、私はそれを行うことはできません。私がテストしたもの:

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

答えて

14

私はそれがうまくいかなかった理由を見つけました。私は同じクラスの他のメソッドからこのメソッドを呼び出しました。したがって、この呼び出しはProxyオブジェクトを経由しないため、注釈は機能しませんでした。

正しい例:

@Service 
@Transactional 
public class MyClass { 

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

@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

は同じ問題を持っていたし、これはそれを修正しました。ありがとう!しかし、同じクラスに '@CachePut'と '@Cachable'を持つのはどうでしょうか? – DOUBL3P