spring本身內置了對Cache的支持,本次記錄的是基於Java API的ConcurrentMap的CacheManager配置。
1、xml文件中增加命名空間
<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 啟用緩存注解功能,這個是必須的,否則注解不會生效,有一個cache-manager屬性用來指定當前所使用的CacheManager對應的bean的名稱,默認是cacheManager -->
<cache:annotation-driven/>
</beans>
<cache:annotation-driven/>有一個cache-manager屬性用來指定當前所使用的CacheManager對應的bean的名稱,默認是cacheManager
2、配置CacheManager
CacheManager是Spring定義的一個用來管理Cache的接口。Spring自身已經為我們提供了兩種CacheManager的實現。一種是基於Java API的ConcurrentMap,另一種是基於第三方Cache實現--EhCache.。
基於ConcurrentMap的配置
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
<!--xxxx對應@Cacheable中的value值-->
<property name="name" value="xxxx"/>
</bean>
</set>
</property>
</bean>
完成以上步驟后,可進行測試下。
第一次調用時,走其中的方法,第二次不走其中方法,直接從緩存中抽取。