Spring配置文件专门为缓存提供了一个cache:命名空间,为了启用Spring缓存,需要在配置文件中导入cache:命名空间。如下
<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
导入命名空间后,启用Spring缓存还要两步:
1.在Spring配置文件中添加<cache:annotation-driven cache-manage="缓存管理器Id"/>,该元素值定Spring根据注解来启用Bean级别或者方法级别的缓存。
2.针对不同的缓存实现配置对应的缓存管理器。
解决方法:对于上面两步,其中第1步非常简单,使用<cache:annotation-driven...../>元素是可通过cache-manager显式指定容器中缓存管理器的id;该属性的默认值为cacheManager,换句话说,如果将容器中缓存管理器的id设为cacheManager,则可以直接<cache:annotation-driven/>。
第2步:则有些麻烦,由于Spring底层可使用大部分主流的Java缓存工具,而不同的缓存工具所需的配置也不同,因此有点麻烦。