Spring的缓存机制非常灵活,可以对容器中任意Bean或者Bean的方法进行缓存,因此这种缓存机制可以在JavaEE应用的任何层次上进行缓存。
Spring缓存底层也是需要借助其他缓存工具来实现,例如EhCache(Hibernate缓存工具),上层则以统一API编程。
要使用Spring缓存,需要以下三步
1.向Spring配置文件导入context:命名空间
2.在Spring配置文件启用缓存,具体是添加
3.配置缓存管理器,不同的缓存实现配置不同,如果是EhCache,需要先配置一个ehcache.xml
例如
1 <?xml version="1.0" encoding="UTF-8"?>
2
3
4
5
7 eternal="false"
8 timeToIdleSeconds="120"
9 timeToLiveSeconds="120"
10 maxElementsOnDisk="10000000"
11 diskExpiryThreadIntervalSeconds="120"
12 memoryStoreEvictionPolicy="LRU"/>
13
14
15 maxElementsInMemory="10000"
16 eternal="false"
17 overflowToDisk="true"
18 timeToIdleSeconds="300"
19 timeToLiveSeconds="600" />
20
上面的ehcache.xml配置了两个缓存区,Spring中的Bean将会缓存在这些缓存区中,一般的,Spring容器中有多少个Bean,就会在ehcache中定义多少个缓存区。
接着在Spring配置文件中配置缓存管理器如下,其中第一个Bean是一个工厂Bean,用来配置EhCache的CacheManager, 第二个Bean才是为Spring缓存配置的缓存管理器,所以将第一个Bean注入第二个Bean。
1
2
3
5
6 class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
7 p:configLocation="classpath:ehcache.xml"
8 p:shared="false" />
9
11
12 class="org.springframework.cache.ehcache.EhCacheCacheManager"
13 p:cacheManager-ref="ehCacheManager" >
14
下面是一个完整的Spring配置,
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:p="http://www.springframework.org/sch