diff --git a/grails-cache/build.gradle b/grails-cache/build.gradle
index 2f7ca078a88..31af1252de1 100644
--- a/grails-cache/build.gradle
+++ b/grails-cache/build.gradle
@@ -60,6 +60,7 @@ dependencies {
testImplementation project(':grails-testing-support-datamapping')
testImplementation project(':grails-testing-support-web')
+ testImplementation testFixtures(project(':grails-core')) // LogCapture
testImplementation 'org.spockframework:spock-core'
testCompileOnly 'org.slf4j:slf4j-nop' // Prevents warning about missing slf4j implementation during compilation
diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/MissingCacheReporter.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/MissingCacheReporter.groovy
new file mode 100644
index 00000000000..893213409b3
--- /dev/null
+++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/MissingCacheReporter.groovy
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.plugin.cache
+
+import java.util.concurrent.ConcurrentHashMap
+
+import groovy.transform.CompileStatic
+import groovy.util.logging.Slf4j
+
+import org.springframework.cache.CacheManager
+
+/**
+ * Reports a cache the cache manager does not have, for the code the cache annotations generate.
+ *
+ *
A cache manager answers null for a name it has no cache of, as {@code JCacheCacheManager} does
+ * for a cache it was not configured with. The annotated method then runs as it does without a cache
+ * manager, and this says so once for each cache manager and name.
+ *
+ * @since 8.0.1
+ */
+@Slf4j
+@CompileStatic
+final class MissingCacheReporter {
+
+ /** The names of the caches reported missing, for each cache manager. */
+ private static final Map> REPORTED = Collections.synchronizedMap(
+ new WeakHashMap>())
+
+ private MissingCacheReporter() {
+ }
+
+ /**
+ * @param cacheManager the cache manager without the cache
+ * @param cacheName the name the annotation gives
+ * @param owner the class of the annotated method
+ */
+ static void report(CacheManager cacheManager, String cacheName, Class> owner) {
+ Set reported = REPORTED.computeIfAbsent(cacheManager) { CacheManager ignored ->
+ ConcurrentHashMap. newKeySet()
+ }
+ if (reported.add(cacheName)) {
+ log.warn('{} does not cache with {}: its cache manager, {}, has no cache of that name, so the methods ' +
+ 'run uncached. Configure the cache in that cache manager.', owner.name, cacheName, cacheManager.getClass().name)
+ }
+ }
+}
diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy
index a4087dcab04..de17f546fd3 100644
--- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy
+++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy
@@ -51,6 +51,7 @@ import org.grails.datastore.gorm.transform.AbstractMethodDecoratingTransformatio
import org.grails.datastore.gorm.transform.AbstractTraitApplyingGormASTTransformation
import org.grails.datastore.mapping.model.config.GormProperties
import org.grails.plugin.cache.GrailsCacheManagerAware
+import org.grails.plugin.cache.MissingCacheReporter
import static org.codehaus.groovy.ast.ClassHelper.CLOSURE_TYPE
import static org.codehaus.groovy.ast.ClassHelper.MAP_TYPE
@@ -59,15 +60,19 @@ import static org.codehaus.groovy.ast.ClassHelper.STRING_TYPE
import static org.codehaus.groovy.ast.ClassHelper.int_TYPE
import static org.codehaus.groovy.ast.ClassHelper.make
import static org.codehaus.groovy.ast.tools.GeneralUtils.args
+import static org.codehaus.groovy.ast.tools.GeneralUtils.block
import static org.codehaus.groovy.ast.tools.GeneralUtils.callX
import static org.codehaus.groovy.ast.tools.GeneralUtils.classX
import static org.codehaus.groovy.ast.tools.GeneralUtils.constX
import static org.codehaus.groovy.ast.tools.GeneralUtils.declS
+import static org.codehaus.groovy.ast.tools.GeneralUtils.ifElseS
import static org.codehaus.groovy.ast.tools.GeneralUtils.ifS
+import static org.codehaus.groovy.ast.tools.GeneralUtils.notNullX
import static org.codehaus.groovy.ast.tools.GeneralUtils.notX
import static org.codehaus.groovy.ast.tools.GeneralUtils.param
import static org.codehaus.groovy.ast.tools.GeneralUtils.params
import static org.codehaus.groovy.ast.tools.GeneralUtils.returnS
+import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt
import static org.codehaus.groovy.ast.tools.GeneralUtils.varX
import static org.grails.datastore.gorm.transform.AstMethodDispatchUtils.callD
@@ -102,6 +107,10 @@ abstract class AbstractCacheTransformation extends AbstractMethodDecoratingTrans
param(MAP_TYPE, 'methodParams')))
private static final ClassNode CACHE_MANAGER_CLASS_NODE = make(CacheManager)
private static final MethodNode GET_CACHE_METHOD_NODE = CACHE_MANAGER_CLASS_NODE.getMethod('getCache', [new Parameter(STRING_TYPE, 'name')] as Parameter[])
+ private static final ClassNode MISSING_CACHE_REPORTER_CLASS_NODE = make(MissingCacheReporter)
+ private static final MethodNode REPORT_MISSING_CACHE_METHOD_NODE = MISSING_CACHE_REPORTER_CLASS_NODE.getMethod('report',
+ [new Parameter(CACHE_MANAGER_CLASS_NODE, 'cacheManager'), new Parameter(STRING_TYPE, 'cacheName'),
+ new Parameter(make(Class), 'owner')] as Parameter[])
private static final MethodNode MAP_PUT_METHOD = MAP_TYPE.getMethod('put', [new Parameter(OBJECT_TYPE, 'key'), new Parameter(OBJECT_TYPE, 'value')] as Parameter[])
public static final String CACHE_ORIGINAL_METHOD_RETURN_VALUE_LOCAL_VARIABLE_NAME = '$_cache_originalMethodReturnValue'
@@ -171,6 +180,29 @@ abstract class AbstractCacheTransformation extends AbstractMethodDecoratingTrans
return cacheVariableExpression
}
+ /**
+ * Adds to the caching block what runs only where the cache manager has the cache the annotation
+ * names, and returns the block to add it to. A cache manager answers null for a name it has no
+ * cache of, as {@code JCacheCacheManager} does for a cache it was not configured with, and the
+ * method then runs as it does without a cache manager, which is reported once.
+ *
+ * @param annotationNode the cache annotation, whose {@code value} names the cache
+ * @param classNode the class the method is in, which the report names
+ * @param cacheVariableExpression the cache declared by {@link #declareCache}
+ * @param cacheBlock the caching block
+ * @return the block that runs where there is a cache
+ */
+ protected BlockStatement whereCacheExists(AnnotationNode annotationNode, ClassNode classNode,
+ VariableExpression cacheVariableExpression, BlockStatement cacheBlock) {
+ BlockStatement whereCacheExists = block()
+ Object cacheName = ((ConstantExpression) annotationNode.getMember('value')).value
+ MethodCallExpression report = callX(classX(MISSING_CACHE_REPORTER_CLASS_NODE), 'report',
+ args(varX(GRAILS_CACHE_MANAGER_PROPERTY_NAME), constX(cacheName), classX(classNode.plainNodeReference)))
+ report.methodTarget = REPORT_MISSING_CACHE_METHOD_NODE
+ cacheBlock.addStatement(ifElseS(notNullX(cacheVariableExpression), whereCacheExists, stmt(report)))
+ return whereCacheExists
+ }
+
protected VariableExpression declareCacheKey(SourceUnit sourceUnit, AnnotationNode annotationNode, ClassNode classNode, MethodNode methodNode, BlockStatement cacheBlock) {
ArgumentListExpression createKeyArgs = args(
constX(classNode.getName()),
diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheEvictTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheEvictTransformation.groovy
index 8dd0d6fa427..921e8b07f79 100644
--- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheEvictTransformation.groovy
+++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheEvictTransformation.groovy
@@ -67,6 +67,9 @@ class CacheEvictTransformation extends AbstractCacheTransformation {
// Cache $_cache_cacheVariable = this.grailsCacheManager.getCache("...");
VariableExpression cacheDeclaration = declareCache(annotationNode, cacheManagerVariableExpression, cachingBlock)
+ // if($_cache_cacheVariable != null) { ... } else { report the missing cache }
+ BlockStatement cacheBlock = whereCacheExists(annotationNode, classNode, cacheDeclaration, cachingBlock)
+
Statement statement
boolean clearAllEntries = false
@@ -82,16 +85,16 @@ class CacheEvictTransformation extends AbstractCacheTransformation {
statement = stmt(callX(cacheDeclaration, 'clear'))
} else {
// def $_method_parameter_map = [name:value]
- declareAndInitializeParameterValueMap(annotationNode, methodNode, cachingBlock)
+ declareAndInitializeParameterValueMap(annotationNode, methodNode, cacheBlock)
// def $_cache_cacheKey = customCacheKeyGenerator.generate(className, methodName, hashCode, $_method_parameter_map)
- VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cachingBlock)
+ VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cacheBlock)
// $_cache_cacheVariable.evict($_cache_cacheKey)
statement = stmt(callX(cacheDeclaration, 'evict', cacheKeyDeclaration))
}
- cachingBlock.addStatement(statement)
+ cacheBlock.addStatement(statement)
newMethodBody.addStatement(
// if(grailsCacheManager != null)
diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy
index 1cfaa52b5f0..4fafeee996e 100644
--- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy
+++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy
@@ -65,14 +65,17 @@ class CachePutTransformation extends AbstractCacheTransformation {
// Cache $_cache_cacheVariable = this.grailsCacheManager.getCache("...");
VariableExpression cacheDeclaration = declareCache(annotationNode, cacheManagerVariableExpression, cachingBlock)
+ // if($_cache_cacheVariable != null) { ... } else { report the missing cache }
+ BlockStatement cacheBlock = whereCacheExists(annotationNode, classNode, cacheDeclaration, cachingBlock)
+
// def $_method_parameter_map = [name:value]
- declareAndInitializeParameterValueMap(annotationNode, methodNode, cachingBlock)
+ declareAndInitializeParameterValueMap(annotationNode, methodNode, cacheBlock)
// def $_cache_cacheKey = customCacheKeyGenerator.generate(className, methodName, hashCode, $_method_parameter_map)
- VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cachingBlock)
+ VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cacheBlock)
VariableExpression originalValueExpr = varX(CACHE_ORIGINAL_METHOD_RETURN_VALUE_LOCAL_VARIABLE_NAME)
- cachingBlock.addStatement(
+ cacheBlock.addStatement(
block(
declS(originalValueExpr, originalMethodCallExpr),
stmt(callD(cacheDeclaration, 'put', args(cacheKeyDeclaration, originalValueExpr))),
diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy
index 2e1ef8ca04f..6dfa54d97f5 100644
--- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy
+++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy
@@ -86,15 +86,18 @@ class CacheableTransformation extends AbstractCacheTransformation {
// Cache $_cache_cacheVariable = this.grailsCacheManager.getCache("...");
VariableExpression cacheDeclaration = declareCache(annotationNode, cacheManagerVariableExpression, cachingBlock)
+ // if($_cache_cacheVariable != null) { ... } else { report the missing cache }
+ BlockStatement cacheBlock = whereCacheExists(annotationNode, classNode, cacheDeclaration, cachingBlock)
+
// def $_method_parameter_map = [name:value]
- declareAndInitializeParameterValueMap(annotationNode, methodNode, cachingBlock)
+ declareAndInitializeParameterValueMap(annotationNode, methodNode, cacheBlock)
// def $_cache_cacheKey = customCacheKeyGenerator.generate(className, methodName, hashCode, $_method_parameter_map)
- VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cachingBlock)
+ VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cacheBlock)
// ValueWrapper $_cache_valueWrapper = $_cache_cacheVariable.get($_cache_cacheKey);
VariableExpression cacheValueWrapper = varX(CACHE_VALUE_WRAPPER_LOCAL_VARIABLE_NAME, make(Cache.ValueWrapper))
- cachingBlock.addStatement(
+ cacheBlock.addStatement(
declS(cacheValueWrapper, callD(cacheDeclaration, 'get', cacheKeyDeclaration))
)
@@ -106,7 +109,7 @@ class CacheableTransformation extends AbstractCacheTransformation {
// return $_cache_originalMethodReturnValue;
// }
VariableExpression originalValueExpr = varX(CACHE_ORIGINAL_METHOD_RETURN_VALUE_LOCAL_VARIABLE_NAME)
- cachingBlock.addStatement(
+ cacheBlock.addStatement(
ifElseS(notNullX(cacheValueWrapper),
returnS(callD(cacheValueWrapper, 'get')),
block(
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy b/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy
index 95ad1363bc3..d6d859e485e 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy
@@ -28,6 +28,7 @@ import org.springframework.cache.Cache
import grails.plugins.Plugin
import org.grails.plugin.cache.GrailsCacheManager
+import org.grails.plugin.cache.GrailsCacheManagerFallback
/**
* Configures the cache plugin.
@@ -80,6 +81,10 @@ class CacheGrailsPlugin extends Plugin {
bean(CustomCacheKeyGenerator).conditionalOnMissingBeanName()
+ // Spring takes grailsCacheManager for the field of a cache-aware class beside a second cache
+ // manager, such as the one cacheUsers defines, where it cannot otherwise choose.
+ bean(GrailsCacheManagerFallback).staticMethod()
+
bean(GrailsCacheManager).conditionalOnMissingBeanName() { CachePluginConfiguration grailsCacheConfiguration ->
if (cacheManagerType == 'GrailsConcurrentLinkedMapCacheManager') {
return new GrailsConcurrentLinkedMapCacheManager(configuration: grailsCacheConfiguration)
diff --git a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy
new file mode 100644
index 00000000000..eab8bdfe92d
--- /dev/null
+++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy
@@ -0,0 +1,294 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.plugin.cache
+
+import java.lang.ref.Reference
+import java.lang.ref.ReferenceQueue
+import java.lang.ref.WeakReference
+import java.util.concurrent.ConcurrentHashMap
+
+import groovy.transform.CompileStatic
+
+import org.springframework.beans.BeansException
+import org.springframework.beans.factory.BeanFactory
+import org.springframework.beans.factory.BeanFactoryAware
+import org.springframework.beans.factory.config.BeanDefinitionHolder
+import org.springframework.beans.factory.config.BeanFactoryPostProcessor
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
+import org.springframework.beans.factory.config.DependencyDescriptor
+import org.springframework.beans.factory.support.AutowireCandidateResolver
+import org.springframework.beans.factory.support.DefaultListableBeanFactory
+import org.springframework.cache.CacheManager
+import org.springframework.core.ResolvableType
+
+/**
+ * Gives a cache-aware class the cache manager named {@code grailsCacheManager} where Spring cannot choose
+ * the cache manager it injects, and leaves Spring's choice as it is everywhere else.
+ *
+ *
{@link GrailsCacheManagerAware} injects a {@code CacheManager} by type. Beside a second cache
+ * manager, such as the one the Spring Security plugin defines when {@code cacheUsers} is set, Spring
+ * cannot choose by type, and falls back to the bean named like the field. A trait's field is renamed in
+ * the class that implements it, so no bean matched, and the application failed to start.
+ *
+ *
This wraps the bean factory's autowire candidate resolver. Spring asks the resolver, before it
+ * resolves a dependency, for a proxy to inject in its place; for the trait's field the resolver answers
+ * with the field's resolution itself. It is Spring's own, for the bean being injected, with one change:
+ * where Spring would fail because it cannot choose, and {@code grailsCacheManager} is one of the cache
+ * managers it cannot choose between, it takes {@code grailsCacheManager}, unless that resolves to null.
+ * Everywhere else Spring chooses as it did: the only cache manager, the one marked primary or the one
+ * with the highest priority, judged at that moment, leaving out the bean being injected. Any other
+ * injection of a cache manager is left alone.
+ *
+ *
As Spring's own resolution of the field would, the resolver registers the bean as depending on the
+ * cache manager it took, and remembers that cache manager for the injection point Spring resolved,
+ * which Spring passes again for the next injection of the bean, as for a prototype's next instance.
+ * Spring's field injection remembers its own choice the same way, until the bean's definition is reset;
+ * then it resolves the field with a new injection point, which this resolver has not seen. The
+ * injection that Spring AOT generates passes a new one every time, and so resolves every time, as it
+ * did. Where the cache manager remembered fails, the field is resolved again, as Spring resolves it
+ * again.
+ *
+ * @since 8.0.1
+ */
+@CompileStatic
+class GrailsCacheManagerFallback implements BeanFactoryPostProcessor {
+
+ static final String CACHE_MANAGER_BEAN_NAME = 'grailsCacheManager'
+
+ /** The name the trait's field has in each class that implements it. */
+ static final String FIELD_NAME = "${GrailsCacheManagerAware.name.replace('.', '_')}__${CACHE_MANAGER_BEAN_NAME}".toString()
+
+ @Override
+ void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
+ if (beanFactory instanceof DefaultListableBeanFactory) {
+ DefaultListableBeanFactory listable = (DefaultListableBeanFactory) beanFactory
+ if (!(listable.autowireCandidateResolver instanceof CandidateResolver)) {
+ listable.autowireCandidateResolver = new CandidateResolver(listable.autowireCandidateResolver)
+ }
+ }
+ }
+
+ /** Whether the dependency is the trait's cache manager field. */
+ static boolean isTraitField(DependencyDescriptor descriptor) {
+ descriptor.field != null && descriptor.field.name == FIELD_NAME && descriptor.field.type == CacheManager &&
+ GrailsCacheManagerAware.isAssignableFrom(descriptor.field.declaringClass)
+ }
+
+ /**
+ * The bean factory's resolver, resolving the trait's field with the fall back to
+ * {@code grailsCacheManager}.
+ */
+ @CompileStatic
+ static class CandidateResolver implements AutowireCandidateResolver, BeanFactoryAware {
+
+ private final AutowireCandidateResolver delegate
+
+ private DefaultListableBeanFactory beanFactory
+
+ /**
+ * The name of the cache manager taken for each injection point Spring resolved, where Spring would
+ * remember it: one bean, of the field's type. Held as long as Spring holds the injection point.
+ */
+ private final Map remembered = new ConcurrentHashMap()
+
+ private final ReferenceQueue