spring自己內置了對Cache的支持,本次記錄的是基於Java API的ConcurrentMap的CacheManager配置。html
一、xml文件中增長命名空間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: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緩存
二、配置CacheManager測試
CacheManager是Spring定義的一個用來管理Cache的接口。Spring自身已經爲咱們提供了兩種CacheManager的實現。一種是基於Java API的ConcurrentMap,另外一種是基於第三方Cache實現--EhCache.。spa
基於ConcurrentMap的配置code
<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>
完成以上步驟後,可進行測試下。xml
第一次調用時,走其中的方法,第二次不走其中方法,直接從緩存中抽取。htm