? @CacheEvict(value="users", allEntries=true)
? public?void delete(Integer id) {
? ? ? System.out.println("delete user by id: " + id);
? }
? ? ? 清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。
? @CacheEvict(value="users", beforeInvocation=true)
? public?void delete(Integer id) {
? ? ? System.out.println("delete user by id: " + id);
? }
? ? ? 其实除了使用@CacheEvict清除缓存元素外,当我们使用Ehcache作为实现时,我们也可以配置Ehcache自身的驱除策略,其是通过Ehcache的配置文件来指定的。由于Ehcache不是本文描述的重点,这里就不多赘述了,想了解更多关于Ehcache的信息,请查看我关于Ehcache的专栏。
? ? ? @Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。
? @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
? ? ? ? @CacheEvict(value = "cache3", allEntries = true) })
? public User find(Integer id) {
? ? ? returnnull;
? }
? ? ? Spring允许我们在配置可缓存的方法时使用自定义的注解,前提是自定义的注解上必须使用对应的注解进行标注。如我们有如下这么一个使用@Cacheable进行标注的自定义注解。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Cacheable(value="users")
public?@interface?MyCacheable {
}
? ? ? 那么在我们需要缓存的方法上使用@MyCacheable进行标注也可以达到同样的效果。
? @MyCacheable
? public User findById(Integer id) {
? ? ? System.out.println("find user by id: " + id);
? ? ? User user = new User();
? ? ? user.setId(id);
? ? ? user.setName("Name" + id);
? ? ? return user;
? }
? ? ? 配置Spring对基于注解的Cache的支持,首先我们需要在Spring的配置文件中引入cache命名空间,其次通过
"1.0" encoding="UTF-8"?>
? 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">
?
? ? ?
? ? ?
? ? ? 此外,
? ? ? 需要注意的是
? ? ? 除了使用注解来声明对Cache的支持外,Spring还支持使用XML来声明对Cache的支持。这主要是通过类似于aop:advice的cache:advice来进行的。在cache命名空间下定义了一个cache:advice元素用来定义一个对于Cache的advice。其需要指定一个cache-manager属性,默认为cacheManager。cache:advice下面可以指定多个cache:caching元素,其有点类似于使用注解时的@Caching注解。cache:caching元素下又可以指定cache:cacheable、cache:cache-put和cache:cache-evict元素,它们类似于使用注解时的@Cacheable、@CachePut和@CacheEvict。下面来看一个示例:
?
? ? ?
? ? ? ?
? ? ? ?