2014-11-02 63 views
1

我使用Spring與配置春天可緩存不

<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 


    <mvc:annotation-driven /> 
    <mvc:resources mapping="/static/**" location="/static/" /> 

    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> 
     <property name="caches"> 
      <set> 
       <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"> 
        <property name="name" value="default"/> 
       </bean> 
      </set> 
     </property> 
    </bean> 

<bean id="bucketsGenerator" class="net.rwchess.utils.PythonBucketsGenerationService"> 
     <constructor-arg index="0" value="/home/bodia/server/jetty/webapps/ROOT/WEB-INF/python/"/> 
    </bean> 
.......... 

<mvc:default-servlet-handler />  
</beans> 

工作,有方法generateBuckets()PythonBucketsGenerationService返回值可以被緩存。因此,我聲明:

@Service 
public class PythonBucketsGenerationService { 

    private String pythonDir; 

    public PythonBucketsGenerationService(String pythonDir) { 
     this.pythonDir = pythonDir; 
    } 

    @Cacheable(value = "buckets") 
    public List<Bucket> generateBuckets(List<TournamentPlayer> players) { 
    ..... 
    } 
} 

的問題是,該方法在每次調用執行即使當List<TournamentPlayer> players哈希碼具有相同的值(I選中)。 TournamentPlayer已正確覆蓋equals()hashCode()。這裏有什麼問題?

+0

你怎麼調用'generateBuckets'方法,從同一個bean'this.generateBuckets(...)'或從其他bean'bucketsGenerator.generateBuckets(...)'? – Ralph 2014-11-02 13:06:14

+0

我通過構造函數arg將桶生成器的引用傳遞給另一個bean,然後調用引用buckets的bean中的generateBuckets生成器 – bvk256 2014-11-02 13:28:03

回答

3

您很可能缺少啓用註釋驅動的緩存配置(緩存:註釋驅動)。看到這個例子:

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:cache="http://www.springframework.org/schema/cache" 
xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> 

    <cache:annotation-driven /> 

</beans> 

到這個頁面,瞭解更多的文檔:http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/cache.html

+0

我最終使用了我的構造器arg自己實現緩存,因爲它是我需要的唯一地方,並且不需要額外的開銷,但是無論如何感謝你的答案。 – bvk256 2014-11-03 21:12:49