Support 'unless' expression for cache veto
Allow @Cachable, @CachePut and equivalent XML configuration to provide
a SpEL expression that can be used to veto putting an item into the
cache. Unlike 'condition' the 'unless' parameter is evaluated after
the method has been called and can therefore reference the #result.
For example:
@Cacheable(value="book",
condition="#name.length < 32",
unless="#result.hardback")
This commit also allows #result to be referenced from @CacheEvict
expressions as long as 'beforeInvocation' is false.
Issue: SPR-8871
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -25,6 +25,7 @@ import org.springframework.cache.annotation.Caching;
|
||||
|
||||
/**
|
||||
* @author Costin Leau
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
@Cacheable("default")
|
||||
public class AnnotatedClassCacheableService implements CacheableService<Object> {
|
||||
@@ -40,6 +41,10 @@ public class AnnotatedClassCacheableService implements CacheableService<Object>
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object unless(int arg) {
|
||||
return arg;
|
||||
}
|
||||
|
||||
@CacheEvict("default")
|
||||
public void invalidate(Object arg1) {
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,6 +20,7 @@ package org.springframework.cache.config;
|
||||
* Basic service interface.
|
||||
*
|
||||
* @author Costin Leau
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public interface CacheableService<T> {
|
||||
|
||||
@@ -39,6 +40,8 @@ public interface CacheableService<T> {
|
||||
|
||||
T conditional(int field);
|
||||
|
||||
T unless(int arg);
|
||||
|
||||
T key(Object arg1, Object arg2);
|
||||
|
||||
T name(Object arg1);
|
||||
|
||||
@@ -27,6 +27,7 @@ import org.springframework.cache.annotation.Caching;
|
||||
* Simple cacheable service
|
||||
*
|
||||
* @author Costin Leau
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class DefaultCacheableService implements CacheableService<Long> {
|
||||
|
||||
@@ -78,6 +79,12 @@ public class DefaultCacheableService implements CacheableService<Long> {
|
||||
return counter.getAndIncrement();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Cacheable(value = "default", unless = "#result > 10")
|
||||
public Long unless(int arg) {
|
||||
return (long) arg;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Cacheable(value = "default", key = "#p0")
|
||||
public Long key(Object arg1, Object arg2) {
|
||||
|
||||
Reference in New Issue
Block a user