From 621a2a8087a3dd1acba89c13c75f6fc483e956cc Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 10:55:21 -0800 Subject: [PATCH 01/20] Find the Grails cache manager when the context has another one GrailsCacheManagerAware, which GrailsCacheAdminService and every class with a cached method implement, autowired one CacheManager. With a second one in the context the injection was ambiguous, and Spring's fallback of matching the field's name did not help, as a trait's field is renamed in the class that implements it. So an application with the cache plugin, which grails-dependencies-starter-web brings in, failed to start once anything else defined a CacheManager, as the Spring Security plugin does with cacheUsers. The trait now takes every cache manager by bean name and uses the one named grailsCacheManager, or where there is none the only one there is, as before. Several and none of that name leave it without one rather than failing startup. --- .../cache/GrailsCacheManagerAware.groovy | 16 +++++- .../cache/CacheAutoConfigurationSpec.groovy | 51 ++++++++++++++++++- 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index 932c5f093f4..e61c7f7bac3 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -39,13 +39,27 @@ trait GrailsCacheManagerAware { @Autowired(required = false) private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() + /** + * Every cache manager in the context, by bean name. Injected as a map rather than as the one + * cache manager because another one, such as the one the Spring Security plugin caches users with + * when {@code cacheUsers} is set, made that injection ambiguous and the context failed to start: + * Spring falls back to matching the field's name, and a trait's field is renamed in the class + * that implements it. + */ @Autowired(required = false) + private Map cacheManagers + private CacheManager grailsCacheManager /** - * @return The Grails cache manager or null if it isn't present + * @return The Grails cache manager, the bean named {@code grailsCacheManager}, or where there is + * none the only cache manager in the context, or null if there is no such cache manager */ CacheManager getGrailsCacheManager() { + if (grailsCacheManager == null && cacheManagers) { + grailsCacheManager = cacheManagers.get('grailsCacheManager') ?: + (cacheManagers.size() == 1 ? cacheManagers.values().first() : null) + } return grailsCacheManager } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 95900ebe6fc..60bd4b69e16 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -20,6 +20,8 @@ package grails.plugin.cache import groovy.transform.CompileStatic +import org.springframework.cache.CacheManager +import org.springframework.cache.concurrent.ConcurrentMapCacheManager import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.core.env.MapPropertySource @@ -27,6 +29,7 @@ import grails.core.DefaultGrailsApplication import grails.core.GrailsApplication import org.grails.plugin.cache.GrailsCacheManager +import org.grails.plugin.cache.GrailsCacheManagerAware import spock.lang.Specification import spock.lang.Unroll @@ -144,6 +147,47 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } + void 'another cache manager in the context, such as the one Spring Security caches users with, is not taken for the Grails one'() { + given: 'Spring Security defines cacheManager when cacheUsers is set' + CacheManager other = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext([:], null, [cacheManager: other]) + + expect: 'the context starts, and what the plugin caches with is its own cache manager' + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(context.getBean('grailsCacheManager')) + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('grailsCacheManager')) + + cleanup: + context.close() + } + + void 'with caching disabled, the one cache manager the context has is used, as before'() { + given: + CacheManager only = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext(['grails.cache.enabled': 'false'], null, [cacheManager: only]) + + expect: + context.getBean(CacheAware).grailsCacheManager.is(only) + + cleanup: + context.close() + } + + void 'with caching disabled and several cache managers, none named grailsCacheManager, none is used'() { + given: + AnnotationConfigApplicationContext context = buildContext(['grails.cache.enabled': 'false'], null, + [cacheManager: new ConcurrentMapCacheManager(), otherCacheManager: new ConcurrentMapCacheManager()]) + + expect: 'the context still starts' + context.getBean(CacheAware).grailsCacheManager == null + + cleanup: + context.close() + } + + /** A class the cache transformations make cache-aware, as they do a service with a cached method. */ + static class CacheAware implements GrailsCacheManagerAware { + } + /** * A plugin wired the way the runtime wires it: with the application context and with a * GrailsApplication carrying the same configuration. Both matter - reading the property back out @@ -160,12 +204,17 @@ class CacheAutoConfigurationSpec extends Specification { @CompileStatic private static AnnotationConfigApplicationContext buildContext( - Map properties, GrailsCacheManager userCacheManager = null) { + Map properties, GrailsCacheManager userCacheManager = null, + Map otherCacheManagers = [:]) { def context = new AnnotationConfigApplicationContext() context.environment.propertySources.addFirst(new MapPropertySource('test', properties)) if (userCacheManager != null) { context.registerBean('grailsCacheManager', GrailsCacheManager, () -> userCacheManager) } + otherCacheManagers.each { String name, CacheManager cacheManager -> + context.registerBean(name, CacheManager, () -> cacheManager) + } + context.registerBean(CacheAware) context.register(CacheAutoConfiguration) context.refresh() return context From 210ee4dadce6e3908404368eda0d4b61072aac12 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 13:11:57 -0800 Subject: [PATCH 02/20] Use the cache manager Spring would have injected, where it can choose one 621a2a8087 took the bean named grailsCacheManager, or the only cache manager. With several, one marked primary and none of that name, as with caching auto-configuration off, it found none, where the injection it replaced used the primary one, so cache annotations neither cached nor evicted. With the plugin's manager there too, it also took that one over an application's own manager marked primary. The trait now asks Spring first, through an ObjectProvider: the only cache manager, or the one marked primary. The bean named grailsCacheManager is used only where Spring cannot choose, which is the case that failed startup. So every context that started before gets the cache manager it had. --- .../cache/GrailsCacheManagerAware.groovy | 25 +++++++++------ .../cache/CacheAutoConfigurationSpec.groovy | 32 +++++++++++++++++-- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index e61c7f7bac3..0b98c9db571 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -21,6 +21,7 @@ package org.grails.plugin.cache import groovy.transform.CompileStatic +import org.springframework.beans.factory.ObjectProvider import org.springframework.beans.factory.annotation.Autowired import org.springframework.cache.CacheManager @@ -40,10 +41,16 @@ trait GrailsCacheManagerAware { private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() /** - * Every cache manager in the context, by bean name. Injected as a map rather than as the one - * cache manager because another one, such as the one the Spring Security plugin caches users with - * when {@code cacheUsers} is set, made that injection ambiguous and the context failed to start: - * Spring falls back to matching the field's name, and a trait's field is renamed in the class + * The cache manager Spring would inject: the only one in the context, or the one marked primary. + */ + @Autowired(required = false) + private ObjectProvider cacheManagerProvider + + /** + * Every cache manager in the context, by bean name, for when Spring cannot choose one. Another cache + * manager, such as the one the Spring Security plugin caches users with when {@code cacheUsers} is + * set, used to make the injection of a single cache manager ambiguous, and the context failed to + * start: Spring falls back to matching the field's name, and a trait's field is renamed in the class * that implements it. */ @Autowired(required = false) @@ -52,13 +59,13 @@ trait GrailsCacheManagerAware { private CacheManager grailsCacheManager /** - * @return The Grails cache manager, the bean named {@code grailsCacheManager}, or where there is - * none the only cache manager in the context, or null if there is no such cache manager + * @return The cache manager Spring would inject, the only one or the one marked primary, or where + * there are several and none is primary the one named {@code grailsCacheManager}, or null if there + * is no such cache manager */ CacheManager getGrailsCacheManager() { - if (grailsCacheManager == null && cacheManagers) { - grailsCacheManager = cacheManagers.get('grailsCacheManager') ?: - (cacheManagers.size() == 1 ? cacheManagers.values().first() : null) + if (grailsCacheManager == null) { + grailsCacheManager = cacheManagerProvider?.getIfUnique() ?: cacheManagers?.get('grailsCacheManager') } return grailsCacheManager } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 60bd4b69e16..21268b429dd 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -20,6 +20,7 @@ package grails.plugin.cache import groovy.transform.CompileStatic +import org.springframework.beans.factory.config.BeanDefinition import org.springframework.cache.CacheManager import org.springframework.cache.concurrent.ConcurrentMapCacheManager import org.springframework.context.annotation.AnnotationConfigApplicationContext @@ -184,6 +185,31 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } + void 'with caching disabled and several cache managers, the one marked primary is used, as Spring chose it before'() { + given: + CacheManager primary = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext(['grails.cache.enabled': 'false'], null, + [cacheManager: new ConcurrentMapCacheManager(), primaryCacheManager: primary], 'primaryCacheManager') + + expect: + context.getBean(CacheAware).grailsCacheManager.is(primary) + + cleanup: + context.close() + } + + void 'a cache manager marked primary is used over the Grails one, as Spring chose it before'() { + given: 'an application\'s own cache manager, marked primary' + CacheManager primary = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext([:], null, [cacheManager: primary], 'cacheManager') + + expect: + context.getBean(CacheAware).grailsCacheManager.is(primary) + + cleanup: + context.close() + } + /** A class the cache transformations make cache-aware, as they do a service with a cached method. */ static class CacheAware implements GrailsCacheManagerAware { } @@ -205,14 +231,16 @@ class CacheAutoConfigurationSpec extends Specification { @CompileStatic private static AnnotationConfigApplicationContext buildContext( Map properties, GrailsCacheManager userCacheManager = null, - Map otherCacheManagers = [:]) { + Map otherCacheManagers = [:], String primary = null) { def context = new AnnotationConfigApplicationContext() context.environment.propertySources.addFirst(new MapPropertySource('test', properties)) if (userCacheManager != null) { context.registerBean('grailsCacheManager', GrailsCacheManager, () -> userCacheManager) } otherCacheManagers.each { String name, CacheManager cacheManager -> - context.registerBean(name, CacheManager, () -> cacheManager) + context.registerBean(name, CacheManager, () -> cacheManager) { BeanDefinition definition -> + definition.primary = name == primary + } } context.registerBean(CacheAware) context.register(CacheAutoConfiguration) From 695525acea186f7505b7b8a460a340c0d17fabc3 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 18:13:10 -0800 Subject: [PATCH 03/20] Take the cache manager named grailsCacheManager before a primary one 210ee4dadc asked Spring for the only or primary cache manager first, so with the plugin's grailsCacheManager and another cache manager marked primary, cache annotations used the other one. The plugin creates its caches in grailsCacheManager and its tag library is wired to it by name, so the annotations now use it too: the bean of that name first, and the only or primary cache manager where there is none of that name. --- .../cache/GrailsCacheManagerAware.groovy | 21 ++++++++++--------- .../cache/CacheAutoConfigurationSpec.groovy | 11 +++++----- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index 0b98c9db571..721695c390a 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -41,17 +41,19 @@ trait GrailsCacheManagerAware { private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() /** - * The cache manager Spring would inject: the only one in the context, or the one marked primary. + * The cache manager Spring would inject, the only one in the context or the one marked primary, for + * when there is none named {@code grailsCacheManager}. */ @Autowired(required = false) private ObjectProvider cacheManagerProvider /** - * Every cache manager in the context, by bean name, for when Spring cannot choose one. Another cache - * manager, such as the one the Spring Security plugin caches users with when {@code cacheUsers} is - * set, used to make the injection of a single cache manager ambiguous, and the context failed to - * start: Spring falls back to matching the field's name, and a trait's field is renamed in the class - * that implements it. + * Every cache manager in the context, by bean name, so that the plugin's own, named + * {@code grailsCacheManager}, is found by that name, as the plugin and its tag library find it. + * Another cache manager, such as the one the Spring Security plugin caches users with when + * {@code cacheUsers} is set, used to make the injection of a single cache manager ambiguous, and + * the context failed to start: Spring falls back to matching the field's name, and a trait's field + * is renamed in the class that implements it. */ @Autowired(required = false) private Map cacheManagers @@ -59,13 +61,12 @@ trait GrailsCacheManagerAware { private CacheManager grailsCacheManager /** - * @return The cache manager Spring would inject, the only one or the one marked primary, or where - * there are several and none is primary the one named {@code grailsCacheManager}, or null if there - * is no such cache manager + * @return The cache manager named {@code grailsCacheManager}, or where there is none the only cache + * manager or the one marked primary, or null if there is no such cache manager */ CacheManager getGrailsCacheManager() { if (grailsCacheManager == null) { - grailsCacheManager = cacheManagerProvider?.getIfUnique() ?: cacheManagers?.get('grailsCacheManager') + grailsCacheManager = cacheManagers?.get('grailsCacheManager') ?: cacheManagerProvider?.getIfUnique() } return grailsCacheManager } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 21268b429dd..616f298654a 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -198,13 +198,14 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } - void 'a cache manager marked primary is used over the Grails one, as Spring chose it before'() { + void 'the Grails cache manager is used over another cache manager marked primary'() { given: 'an application\'s own cache manager, marked primary' - CacheManager primary = new ConcurrentMapCacheManager() - AnnotationConfigApplicationContext context = buildContext([:], null, [cacheManager: primary], 'cacheManager') + AnnotationConfigApplicationContext context = buildContext([:], null, + [cacheManager: new ConcurrentMapCacheManager()], 'cacheManager') - expect: - context.getBean(CacheAware).grailsCacheManager.is(primary) + expect: 'the one the plugin creates its caches in, and its tag library uses' + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('grailsCacheManager')) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(context.getBean('grailsCacheManager')) cleanup: context.close() From ef8a89832bd85494578d3800ce6354fce689ab3d Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 19:37:59 -0800 Subject: [PATCH 04/20] Look up the cache manager without creating the others Injecting every cache manager by name created each of them when a cache-aware bean was, including one declared lazy that the injection this replaced never created, so a lazy cache manager whose store was down failed startup. The trait now looks the cache manager up in the bean factory when it is first asked for: grailsCacheManager by name, or the only or primary one through the bean provider. Both work from the bean definitions, and only the cache manager returned is created. --- .../cache/GrailsCacheManagerAware.groovy | 35 ++++++++--------- .../cache/CacheAutoConfigurationSpec.groovy | 39 ++++++++++++++++++- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index 721695c390a..c05b0fe401f 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -21,7 +21,7 @@ package org.grails.plugin.cache import groovy.transform.CompileStatic -import org.springframework.beans.factory.ObjectProvider +import org.springframework.beans.factory.BeanFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.cache.CacheManager @@ -41,32 +41,29 @@ trait GrailsCacheManagerAware { private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() /** - * The cache manager Spring would inject, the only one in the context or the one marked primary, for - * when there is none named {@code grailsCacheManager}. + * Where the cache manager is looked up, when it is first asked for. Looked up rather than injected: + * another cache manager, such as the one the Spring Security plugin caches users with when + * {@code cacheUsers} is set, made the injection of a single cache manager ambiguous, and the context + * failed to start, as Spring falls back to matching the field's name and a trait's field is renamed + * in the class that implements it. Injecting every cache manager instead would create those declared + * lazy, which the injection never did. */ @Autowired(required = false) - private ObjectProvider cacheManagerProvider - - /** - * Every cache manager in the context, by bean name, so that the plugin's own, named - * {@code grailsCacheManager}, is found by that name, as the plugin and its tag library find it. - * Another cache manager, such as the one the Spring Security plugin caches users with when - * {@code cacheUsers} is set, used to make the injection of a single cache manager ambiguous, and - * the context failed to start: Spring falls back to matching the field's name, and a trait's field - * is renamed in the class that implements it. - */ - @Autowired(required = false) - private Map cacheManagers + private BeanFactory cacheManagerSource private CacheManager grailsCacheManager /** - * @return The cache manager named {@code grailsCacheManager}, or where there is none the only cache - * manager or the one marked primary, or null if there is no such cache manager + * @return The cache manager named {@code grailsCacheManager}, which the plugin creates its caches in + * and its tag library uses, or where there is none the only cache manager or the one marked primary, + * or null if there is no such cache manager. Only the cache manager returned is created. */ CacheManager getGrailsCacheManager() { - if (grailsCacheManager == null) { - grailsCacheManager = cacheManagers?.get('grailsCacheManager') ?: cacheManagerProvider?.getIfUnique() + if (grailsCacheManager == null && cacheManagerSource != null) { + grailsCacheManager = cacheManagerSource.containsBean('grailsCacheManager') && + cacheManagerSource.isTypeMatch('grailsCacheManager', CacheManager) ? + cacheManagerSource.getBean('grailsCacheManager', CacheManager) : + cacheManagerSource.getBeanProvider(CacheManager).getIfUnique() } return grailsCacheManager } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 616f298654a..4a92f574899 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -18,6 +18,8 @@ */ package grails.plugin.cache +import java.util.function.Supplier + import groovy.transform.CompileStatic import org.springframework.beans.factory.config.BeanDefinition @@ -211,6 +213,35 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } + void 'a lazy cache manager is not created to find the Grails one'() { + given: 'a lazy cache manager whose store is down, which the injection this replaced never created' + AnnotationConfigApplicationContext context = buildContext([:], null, [:], null, [unreachableCacheManager: STORE_DOWN]) + + expect: 'the context starts, and the Grails cache manager is used' + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('grailsCacheManager')) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(context.getBean('grailsCacheManager')) + + cleanup: + context.close() + } + + void 'a lazy cache manager is not created to find the primary one where there is no Grails one'() { + given: + CacheManager primary = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext(['grails.cache.enabled': 'false'], null, + [primaryCacheManager: primary], 'primaryCacheManager', [unreachableCacheManager: STORE_DOWN]) + + expect: + context.getBean(CacheAware).grailsCacheManager.is(primary) + + cleanup: + context.close() + } + + private static final Supplier STORE_DOWN = { -> + throw new IllegalStateException('the cache store is down') + } as Supplier + /** A class the cache transformations make cache-aware, as they do a service with a cached method. */ static class CacheAware implements GrailsCacheManagerAware { } @@ -232,7 +263,8 @@ class CacheAutoConfigurationSpec extends Specification { @CompileStatic private static AnnotationConfigApplicationContext buildContext( Map properties, GrailsCacheManager userCacheManager = null, - Map otherCacheManagers = [:], String primary = null) { + Map otherCacheManagers = [:], String primary = null, + Map> lazyCacheManagers = [:]) { def context = new AnnotationConfigApplicationContext() context.environment.propertySources.addFirst(new MapPropertySource('test', properties)) if (userCacheManager != null) { @@ -243,6 +275,11 @@ class CacheAutoConfigurationSpec extends Specification { definition.primary = name == primary } } + lazyCacheManagers.each { String name, Supplier cacheManager -> + context.registerBean(name, CacheManager, cacheManager) { BeanDefinition definition -> + definition.lazyInit = true + } + } context.registerBean(CacheAware) context.register(CacheAutoConfiguration) context.refresh() From 4aaa670cd8737857fe58ce64853bc021f9534f65 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 19:45:45 -0800 Subject: [PATCH 05/20] Resolve the cache manager as Spring injected it, checked against the injection The lookup reimplemented Spring's choice through the bean provider, and a matrix of every arrangement of cache managers against what Spring injected into the trait's old field found 16 that differed: a cache manager that is not an autowire candidate, or not a default one, was used where the injection used none or another; a fallback lost to a non-default one; and two primary or two equally high priority cache managers threw on the first cached call instead of failing startup as before. GrailsCacheManagerLookup now takes grailsCacheManager by name, as the plugin and its tag library do, and otherwise resolves the dependency with Spring's own resolveDependency, against an injection point like the trait's old field, so every other choice is the injection's. Where Spring cannot choose there is no cache manager, and a warning names the class and the cache managers. The trait looks up once, so a lookup that finds none is not repeated on every cached call. GrailsCacheManagerLookupMatrixSpec runs 342 arrangements, each in a context of its own against a bean with the old injection, and checks which cache manager is used and that none is created the injection would not have created. --- grails-cache/build.gradle | 1 + .../cache/GrailsCacheManagerAware.groovy | 27 ++- .../cache/GrailsCacheManagerLookup.groovy | 87 ++++++++ .../GrailsCacheManagerLookupMatrixSpec.groovy | 204 ++++++++++++++++++ 4 files changed, 305 insertions(+), 14 deletions(-) create mode 100644 grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy create mode 100644 grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy 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/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index c05b0fe401f..3230d377935 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -41,29 +41,28 @@ trait GrailsCacheManagerAware { private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() /** - * Where the cache manager is looked up, when it is first asked for. Looked up rather than injected: - * another cache manager, such as the one the Spring Security plugin caches users with when - * {@code cacheUsers} is set, made the injection of a single cache manager ambiguous, and the context - * failed to start, as Spring falls back to matching the field's name and a trait's field is renamed - * in the class that implements it. Injecting every cache manager instead would create those declared - * lazy, which the injection never did. + * Where the cache manager is looked up, the first time it is asked for, rather than injected: another + * cache manager, such as the one the Spring Security plugin caches users with when {@code cacheUsers} + * is set, made the injection of a single cache manager ambiguous, and the context failed to start, + * as Spring falls back to matching the field's name and a trait's field is renamed in the class that + * implements it. */ @Autowired(required = false) private BeanFactory cacheManagerSource private CacheManager grailsCacheManager + private boolean grailsCacheManagerLookedUp + /** - * @return The cache manager named {@code grailsCacheManager}, which the plugin creates its caches in - * and its tag library uses, or where there is none the only cache manager or the one marked primary, - * or null if there is no such cache manager. Only the cache manager returned is created. + * @return The cache manager named {@code grailsCacheManager}, or where there is none the one Spring + * would inject into a {@code CacheManager} field, or null if there is none or Spring cannot choose + * one. See {@link GrailsCacheManagerLookup}. */ CacheManager getGrailsCacheManager() { - if (grailsCacheManager == null && cacheManagerSource != null) { - grailsCacheManager = cacheManagerSource.containsBean('grailsCacheManager') && - cacheManagerSource.isTypeMatch('grailsCacheManager', CacheManager) ? - cacheManagerSource.getBean('grailsCacheManager', CacheManager) : - cacheManagerSource.getBeanProvider(CacheManager).getIfUnique() + if (grailsCacheManager == null && !grailsCacheManagerLookedUp && cacheManagerSource != null) { + grailsCacheManager = GrailsCacheManagerLookup.find(cacheManagerSource, getClass()) + grailsCacheManagerLookedUp = true } return grailsCacheManager } diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy new file mode 100644 index 00000000000..a7503a1717c --- /dev/null +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy @@ -0,0 +1,87 @@ +/* + * 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.reflect.Field + +import groovy.transform.CompileStatic +import groovy.util.logging.Slf4j + +import org.springframework.beans.factory.BeanFactory +import org.springframework.beans.factory.NoUniqueBeanDefinitionException +import org.springframework.beans.factory.config.AutowireCapableBeanFactory +import org.springframework.beans.factory.config.DependencyDescriptor +import org.springframework.cache.CacheManager + +/** + * Finds the cache manager a {@link GrailsCacheManagerAware} class caches with. + * + *

The bean named {@code grailsCacheManager} comes first, as the plugin creates its caches in it + * and its tag library is wired to it by name. Without one, the cache manager is resolved exactly as + * Spring resolves a {@code CacheManager} field marked {@code @Autowired(required = false)}, which is + * how the trait used to receive it: the only candidate, or the one marked primary or of the highest + * priority, with lazy beans, fallback beans and beans that are not autowire candidates treated as + * that injection treats them, and only the cache manager chosen created. Where Spring cannot choose, + * which failed startup when the trait was injected, there is no cache manager, and a warning says + * why.

+ * + * @since 8.0.1 + */ +@Slf4j +@CompileStatic +final class GrailsCacheManagerLookup { + + static final String BEAN_NAME = 'grailsCacheManager' + + /** The injection point the trait declared, which is resolved as Spring resolved it. */ + private static final Field INJECTION_POINT = InjectionPoint.getDeclaredField(BEAN_NAME) + + private GrailsCacheManagerLookup() { + } + + /** + * @param beanFactory where the cache manager is looked up + * @param owner the class that caches with it, which a warning names + * @return the cache manager, or null if there is none or Spring cannot choose one + */ + static CacheManager find(BeanFactory beanFactory, Class owner) { + if (beanFactory.containsBean(BEAN_NAME) && beanFactory.isTypeMatch(BEAN_NAME, CacheManager)) { + return beanFactory.getBean(BEAN_NAME, CacheManager) + } + if (!(beanFactory instanceof AutowireCapableBeanFactory)) { + return beanFactory.getBeanProvider(CacheManager).getIfUnique() + } + try { + return (CacheManager) ((AutowireCapableBeanFactory) beanFactory) + .resolveDependency(new DependencyDescriptor(INJECTION_POINT, false), null) + } + catch (NoUniqueBeanDefinitionException e) { + log.warn('{} does not cache: there is no cache manager named {}, and Spring cannot choose among {}. ' + + 'Mark one of them primary, or define the one to cache with as {}.', + owner.name, BEAN_NAME, e.beanNamesFound, BEAN_NAME) + return null + } + } + + @CompileStatic + private static class InjectionPoint { + + CacheManager grailsCacheManager + } +} diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy new file mode 100644 index 00000000000..8eea2862281 --- /dev/null +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy @@ -0,0 +1,204 @@ +/* + * 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.function.Supplier + +import jakarta.annotation.Priority + +import ch.qos.logback.classic.Level +import org.springframework.beans.BeansException +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.config.BeanDefinitionCustomizer +import org.springframework.beans.factory.support.AbstractBeanDefinition +import org.springframework.cache.CacheManager +import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import org.springframework.context.annotation.AnnotationConfigUtils +import org.springframework.context.support.GenericApplicationContext +import spock.lang.Shared +import spock.lang.Specification + +import org.apache.grails.core.testing.support.LogCapture + +/** + * Which cache manager a cache-aware class gets, for every arrangement of cache managers, against the + * oracle of what Spring injected into the trait's {@code @Autowired(required = false) CacheManager} + * field before it looked the cache manager up. + * + *

The deliberate differences: a cache manager named {@code grailsCacheManager} is used whenever + * there is one, as the plugin and its tag library use it by name; and where Spring cannot choose, which + * failed startup, there is none. Either way no cache manager is created that the injection would not + * have created, other than the one returned.

+ */ +class GrailsCacheManagerLookupMatrixSpec extends Specification { + + private static final List NAMED = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType'] + + private static final List OTHER = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', 'priority'] + + @Shared + List> rows = arrangements() + + void 'the cache manager a cache-aware class gets matches what Spring injected, except where deliberate'() { + expect: 'every arrangement, each run against the oracle in a context of its own' + List mismatches = [] + rows.each { Map row -> + Map oracle = run(row, Injected) + Map lookup = run(row, CacheAware) + Object expected + if (row.containsKey(GrailsCacheManagerLookup.BEAN_NAME) && row[GrailsCacheManagerLookup.BEAN_NAME] != 'wrongType') { + expected = GrailsCacheManagerLookup.BEAN_NAME + } + else { + expected = oracle.failed ? null : oracle.chosen + } + List allowedToCreate = ((List) oracle.created) + (expected ? [expected as String] : []) + if (lookup.failed) { + mismatches << "${row}: the lookup failed: ${lookup.failure}".toString() + } + else if (lookup.chosen != expected) { + mismatches << "${row}: got ${lookup.chosen}, expected ${expected} (Spring injected ${oracle.failed ? 'nothing, it failed' : oracle.chosen})".toString() + } + else if (!allowedToCreate.containsAll((List) lookup.created)) { + mismatches << "${row}: created ${lookup.created}, where the injection created ${oracle.created}".toString() + } + } + mismatches == [] + } + + void 'the matrix covers the arrangements it says it does'() { + expect: 'six arrangements of the named one, and none, one or two of the seven others' + rows.size() == NAMED.size() * (1 + OTHER.size() + OTHER.size() * OTHER.size()) + } + + void 'where Spring cannot choose, the class does not cache, and a warning says why'() { + given: 'two cache managers, neither primary nor named grailsCacheManager, which failed startup when injected' + GenericApplicationContext context = context([first: 'plain', second: 'plain'], [:]) + LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.WARN) + + when: + CacheManager found = context.getBean('probe', CacheAware).grailsCacheManager + + then: + found == null + log.events*.formattedMessage == ["${CacheAware.name} does not cache: there is no cache manager named grailsCacheManager, " + + 'and Spring cannot choose among [first, second]. Mark one of them primary, or define the one to cache with as ' + + 'grailsCacheManager.'] as List + + cleanup: + log?.close() + context?.close() + } + + void 'the first answer stands, as an injected cache manager did, so a lookup that finds none is not repeated'() { + given: 'a context with no cache manager' + GenericApplicationContext context = context([:], [:]) + CacheAware aware = context.getBean('probe', CacheAware) + + when: 'one is defined after the first lookup' + CacheManager first = aware.grailsCacheManager + context.registerBean('later', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) + + then: 'it would be found, but the lookup is not made again' + first == null + context.getBean('later') instanceof CacheManager + aware.grailsCacheManager == null + + cleanup: + context.close() + } + + private Map run(Map row, Class probe) { + Map instances = [:] + List created = [] + GenericApplicationContext context = context(row, instances, created, probe) + List atStartup = new ArrayList<>(created) + Map result = [failed: false] + try { + Object bean = context.getBean('probe') + CacheManager chosen = probe == Injected ? ((Injected) bean).injected : ((CacheAware) bean).grailsCacheManager + result.chosen = chosen == null ? null : instances.find { String name, CacheManager instance -> instance.is(chosen) }?.key + } + catch (BeansException e) { + result.failed = true + result.failure = e.message + } + result.created = created - atStartup + context.close() + result + } + + private GenericApplicationContext context(Map row, Map instances, + List created = [], Class probe = CacheAware) { + GenericApplicationContext context = new GenericApplicationContext() + AnnotationConfigUtils.registerAnnotationConfigProcessors(context) + row.each { String name, String kind -> + if (kind == 'wrongType') { + context.registerBean(name, String, { -> 'not a cache manager' } as Supplier) + return + } + Class type = kind == 'priority' ? HighPriorityCacheManager : ConcurrentMapCacheManager + Supplier supplier = { -> + created << name + CacheManager instance = type.getDeclaredConstructor().newInstance() + instances[name] = instance + instance + } as Supplier + BeanDefinitionCustomizer customizer = { BeanDefinition definition -> + AbstractBeanDefinition bean = (AbstractBeanDefinition) definition + bean.primary = kind == 'primary' + bean.lazyInit = kind == 'lazy' + bean.autowireCandidate = kind != 'notCandidate' + bean.fallback = kind == 'fallback' + bean.defaultCandidate = kind != 'notDefault' + } as BeanDefinitionCustomizer + context.registerBean(name, (Class) type, supplier, customizer) + } + BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer + context.registerBean('probe', (Class) probe, lazy) + context.refresh() + context + } + + private static List> arrangements() { + List> others = [[:]] + OTHER.each { String first -> others << [first: first] } + OTHER.each { String first -> OTHER.each { String second -> others << [first: first, second: second] } } + NAMED.collectMany { String named -> + others.collect { Map other -> + named == 'absent' ? other : ([(GrailsCacheManagerLookup.BEAN_NAME): named] + other) + } + } + } + + /** What Spring injected into the trait's field, under a name that, like the trait's renamed field, matches no bean. */ + static class Injected { + + @Autowired(required = false) + CacheManager injected + } + + static class CacheAware implements GrailsCacheManagerAware { + } + + @Priority(1) + static class HighPriorityCacheManager extends ConcurrentMapCacheManager { + } +} From bba6ff29f6b591b47211ff4ed2dbfd1e217320df Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 20:07:32 -0800 Subject: [PATCH 06/20] Choose the cache manager when the bean is created, keeping the trait's fields The lookup added fields to GrailsCacheManagerAware. A trait's fields are compiled into each class that implements it, so a class compiled against 8.0.0, such as a cached service in a plugin, lacked them, and the new trait's code threw AbstractMethodError on every cached call where no cache manager had been injected. The lookup also ran on the first call, unsynchronised, so a concurrent first call could see no cache manager, and failures moved from startup to every call. The trait keeps exactly its 8.0.0 fields. Its field is no longer injected; an @Autowired method sets it when the bean is created, from the BeanFactory and an ObjectProvider, as the injection did. A class compiled against 8.0.0 keeps injecting its own field. Without one named grailsCacheManager, the cache manager is the provider's getIfAvailable, which is Spring's injection resolution for the method's own parameter and bean. Where Spring cannot choose, the warning gives Spring's reason, and a primary cache manager passed over for grailsCacheManager is logged once at INFO level. A spec compiles a cached class against the 8.0.0 trait and loads only that class beside this one; against the previous lookup it fails with AbstractMethodError. The cache guide and section 94 of the upgrade guide describe which cache manager is used. --- .../cache/GrailsCacheManagerAware.groovy | 35 +++--- .../cache/GrailsCacheManagerLookup.groovy | 63 +++++----- .../GrailsCacheManagerLookupMatrixSpec.groovy | 117 +++++++++++++++++- .../GrailsCacheManagerAware-8.0.0.groovy.txt | 58 +++++++++ .../guide/cache/cacheUsage/cacheManager.adoc | 4 + .../src/en/guide/upgrading/upgrading80x.adoc | 12 ++ 6 files changed, 241 insertions(+), 48 deletions(-) create mode 100644 grails-cache/src/test/resources/org/grails/plugin/cache/GrailsCacheManagerAware-8.0.0.groovy.txt diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index 3230d377935..a787e78a4f4 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -22,6 +22,7 @@ package org.grails.plugin.cache import groovy.transform.CompileStatic import org.springframework.beans.factory.BeanFactory +import org.springframework.beans.factory.ObjectProvider import org.springframework.beans.factory.annotation.Autowired import org.springframework.cache.CacheManager @@ -41,29 +42,31 @@ trait GrailsCacheManagerAware { private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() /** - * Where the cache manager is looked up, the first time it is asked for, rather than injected: another - * cache manager, such as the one the Spring Security plugin caches users with when {@code cacheUsers} - * is set, made the injection of a single cache manager ambiguous, and the context failed to start, - * as Spring falls back to matching the field's name and a trait's field is renamed in the class that - * implements it. + * Set by {@link #injectGrailsCacheManager} rather than injected. The trait keeps exactly the fields + * it had, so that a class compiled against an earlier version, which declares them itself, works + * with this one. */ - @Autowired(required = false) - private BeanFactory cacheManagerSource - private CacheManager grailsCacheManager - private boolean grailsCacheManagerLookedUp + /** + * Called by Spring when the class is created as a bean, where the trait's field used to be + * injected: another cache manager, such as the one the Spring Security plugin caches users with + * when {@code cacheUsers} is set, made that injection ambiguous, and the context failed to start, + * as Spring falls back to matching the field's name and a trait's field is renamed in the class + * that implements it. See {@link GrailsCacheManagerLookup} for which cache manager is chosen. + * + * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up + * @param cacheManagers the cache manager Spring would inject, where there is none of that name + */ + @Autowired(required = false) + void injectGrailsCacheManager(BeanFactory beanFactory, ObjectProvider cacheManagers) { + grailsCacheManager = GrailsCacheManagerLookup.find(beanFactory, cacheManagers, getClass()) + } /** - * @return The cache manager named {@code grailsCacheManager}, or where there is none the one Spring - * would inject into a {@code CacheManager} field, or null if there is none or Spring cannot choose - * one. See {@link GrailsCacheManagerLookup}. + * @return The cache manager this class caches with, or null if it has none */ CacheManager getGrailsCacheManager() { - if (grailsCacheManager == null && !grailsCacheManagerLookedUp && cacheManagerSource != null) { - grailsCacheManager = GrailsCacheManagerLookup.find(cacheManagerSource, getClass()) - grailsCacheManagerLookedUp = true - } return grailsCacheManager } diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy index a7503a1717c..5978114692f 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy @@ -18,28 +18,28 @@ */ package org.grails.plugin.cache -import java.lang.reflect.Field - import groovy.transform.CompileStatic import groovy.util.logging.Slf4j import org.springframework.beans.factory.BeanFactory import org.springframework.beans.factory.NoUniqueBeanDefinitionException -import org.springframework.beans.factory.config.AutowireCapableBeanFactory -import org.springframework.beans.factory.config.DependencyDescriptor +import org.springframework.beans.factory.ObjectProvider +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory import org.springframework.cache.CacheManager /** - * Finds the cache manager a {@link GrailsCacheManagerAware} class caches with. + * Chooses the cache manager a {@link GrailsCacheManagerAware} class caches with, when Spring creates + * it. * *

The bean named {@code grailsCacheManager} comes first, as the plugin creates its caches in it - * and its tag library is wired to it by name. Without one, the cache manager is resolved exactly as - * Spring resolves a {@code CacheManager} field marked {@code @Autowired(required = false)}, which is - * how the trait used to receive it: the only candidate, or the one marked primary or of the highest - * priority, with lazy beans, fallback beans and beans that are not autowire candidates treated as - * that injection treats them, and only the cache manager chosen created. Where Spring cannot choose, - * which failed startup when the trait was injected, there is no cache manager, and a warning says - * why.

+ * and its tag library is wired to it by name; a cache manager marked primary is passed over for it, + * which is logged once. Without one, the cache manager is the one Spring resolves for the + * {@code ObjectProvider} it is given, which is the one it injected into the trait's + * {@code @Autowired(required = false)} field: the only candidate, or the one marked primary or of the + * highest priority, with lazy beans, fallback beans and beans that are not autowire candidates + * treated as that injection treated them, and only the cache manager chosen created. Where Spring + * cannot choose, which failed startup when the field was injected, there is no cache manager, and a + * warning says why.

* * @since 8.0.1 */ @@ -49,39 +49,46 @@ final class GrailsCacheManagerLookup { static final String BEAN_NAME = 'grailsCacheManager' - /** The injection point the trait declared, which is resolved as Spring resolved it. */ - private static final Field INJECTION_POINT = InjectionPoint.getDeclaredField(BEAN_NAME) + /** The bean factories a primary cache manager passed over has been reported for. */ + private static final Set REPORTED = Collections.synchronizedSet( + Collections.newSetFromMap(new WeakHashMap())) private GrailsCacheManagerLookup() { } /** - * @param beanFactory where the cache manager is looked up + * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up + * @param cacheManagers the cache manager Spring would inject * @param owner the class that caches with it, which a warning names * @return the cache manager, or null if there is none or Spring cannot choose one */ - static CacheManager find(BeanFactory beanFactory, Class owner) { + static CacheManager find(BeanFactory beanFactory, ObjectProvider cacheManagers, Class owner) { if (beanFactory.containsBean(BEAN_NAME) && beanFactory.isTypeMatch(BEAN_NAME, CacheManager)) { + reportPrimaryPassedOver(beanFactory) return beanFactory.getBean(BEAN_NAME, CacheManager) } - if (!(beanFactory instanceof AutowireCapableBeanFactory)) { - return beanFactory.getBeanProvider(CacheManager).getIfUnique() - } try { - return (CacheManager) ((AutowireCapableBeanFactory) beanFactory) - .resolveDependency(new DependencyDescriptor(INJECTION_POINT, false), null) + return cacheManagers.getIfAvailable() } catch (NoUniqueBeanDefinitionException e) { - log.warn('{} does not cache: there is no cache manager named {}, and Spring cannot choose among {}. ' + - 'Mark one of them primary, or define the one to cache with as {}.', - owner.name, BEAN_NAME, e.beanNamesFound, BEAN_NAME) + log.warn('{} does not cache: there is no cache manager named {}, and Spring cannot choose one. {} ' + + 'Define the one to cache with as {}.', owner.name, BEAN_NAME, e.message, BEAN_NAME) return null } } - @CompileStatic - private static class InjectionPoint { - - CacheManager grailsCacheManager + private static void reportPrimaryPassedOver(BeanFactory beanFactory) { + if (!log.infoEnabled || !(beanFactory instanceof ConfigurableListableBeanFactory)) { + return + } + ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) beanFactory + List primary = listable.getBeanNamesForType(CacheManager, true, false).findAll { String name -> + name != BEAN_NAME && !(BEAN_NAME in listable.getAliases(name)) && + listable.containsBeanDefinition(name) && listable.getBeanDefinition(name).primary + } + if (primary && REPORTED.add(beanFactory)) { + log.info('Grails caches with the cache manager named {}, not with {}, which is marked primary. ' + + 'Define the one to cache with as {}.', BEAN_NAME, primary.join(', '), BEAN_NAME) + } } } diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy index 8eea2862281..ae0cbecd0ce 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy @@ -32,6 +32,9 @@ import org.springframework.cache.CacheManager import org.springframework.cache.concurrent.ConcurrentMapCacheManager import org.springframework.context.annotation.AnnotationConfigUtils import org.springframework.context.support.GenericApplicationContext +import org.codehaus.groovy.control.CompilationUnit +import org.codehaus.groovy.control.CompilerConfiguration +import org.codehaus.groovy.tools.GroovyClass import spock.lang.Shared import spock.lang.Specification @@ -96,18 +99,73 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { when: CacheManager found = context.getBean('probe', CacheAware).grailsCacheManager + then: 'it names the class and the cache managers, in Spring\'s words' + found == null + log.events.size() == 1 + log.events[0].formattedMessage.startsWith("${CacheAware.name} does not cache: there is no cache manager named grailsCacheManager") + log.events[0].formattedMessage.contains('first,second') + + cleanup: + log?.close() + context?.close() + } + + void 'two cache managers marked primary are reported in Spring\'s words, rather than as a list it does not give'() { + given: + GenericApplicationContext context = context([first: 'primary', second: 'primary'], [:]) + LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.WARN) + + when: + CacheManager found = context.getBean('probe', CacheAware).grailsCacheManager + then: found == null - log.events*.formattedMessage == ["${CacheAware.name} does not cache: there is no cache manager named grailsCacheManager, " + - 'and Spring cannot choose among [first, second]. Mark one of them primary, or define the one to cache with as ' + - 'grailsCacheManager.'] as List + log.events.size() == 1 + log.events[0].formattedMessage.contains("more than one 'primary' bean found") + !log.events[0].formattedMessage.contains('null') cleanup: log?.close() context?.close() } - void 'the first answer stands, as an injected cache manager did, so a lookup that finds none is not repeated'() { + void 'a primary cache manager passed over for grailsCacheManager is reported once'() { + given: 'an application cache manager marked primary, and two cache-aware beans' + GenericApplicationContext context = context([grailsCacheManager: 'plain', redis: 'primary'], [:]) + context.registerBean('another', CacheAware, { -> new CacheAware() } as Supplier) + LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) + + when: + context.getBean('probe', CacheAware).grailsCacheManager + context.getBean('another', CacheAware).grailsCacheManager + + then: + log.events*.formattedMessage == ['Grails caches with the cache manager named grailsCacheManager, not with redis, ' + + 'which is marked primary. Define the one to cache with as grailsCacheManager.'] + + cleanup: + log?.close() + context?.close() + } + + void 'no primary cache manager is reported where grailsCacheManager is an alias of the primary one'() { + given: 'the primary cache manager, under another name, aliased as grailsCacheManager' + GenericApplicationContext context = context([redis: 'primary'], [:]) + context.registerAlias('redis', 'grailsCacheManager') + LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) + + when: + context.getBean('probe', CacheAware).grailsCacheManager + + then: + log.events == [] + + cleanup: + log?.close() + context?.close() + } + + void 'the cache manager is chosen when the bean is created, as an injected one was'() { given: 'a context with no cache manager' GenericApplicationContext context = context([:], [:]) CacheAware aware = context.getBean('probe', CacheAware) @@ -125,6 +183,57 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { context.close() } + void 'a class compiled against the trait 8.0.0 shipped works with this one'() { + given: 'a cached class compiled together with that trait, of which only the class is loaded beside this one' + Class compiled = compiledAgainst800(''' + package compat + class OldCacheAware implements org.grails.plugin.cache.GrailsCacheManagerAware { + } + ''', 'compat.OldCacheAware') + + expect: 'created on its own, it has no cache manager, rather than throwing' + compiled.getDeclaredConstructor().newInstance().grailsCacheManager == null + + when: 'created as a bean, it is injected through the field it declares, as with 8.0.0' + CacheManager only = new ConcurrentMapCacheManager() + GenericApplicationContext context = new GenericApplicationContext() + AnnotationConfigUtils.registerAnnotationConfigProcessors(context) + context.registerBean('cacheManager', CacheManager, { -> only } as Supplier) + context.registerBean('old', (Class) compiled) + context.refresh() + + then: + context.getBean('old').grailsCacheManager.is(only) + + cleanup: + context?.close() + } + + /** + * Compiles the source with the trait as 8.0.0 shipped it, and loads only the class, so that the + * trait it runs against is this one, as for a plugin compiled against 8.0.0. + */ + private Class compiledAgainst800(String source, String className) { + String trait800 = getClass().getResource('GrailsCacheManagerAware-8.0.0.groovy.txt').text + CompilationUnit unit = new CompilationUnit(new CompilerConfiguration(), null, new GroovyClassLoader(getClass().classLoader)) + unit.addSource('GrailsCacheManagerAware.groovy', trait800) + unit.addSource('OldCacheAware.groovy', source) + unit.compile() + Map classes = unit.classes.collectEntries { GroovyClass compiled -> [(compiled.name): compiled.bytes] } + assert classes.keySet().any { it.startsWith('org.grails.plugin.cache.GrailsCacheManagerAware') } + ClassLoader loader = new ClassLoader(getClass().classLoader) { + @Override + protected Class findClass(String name) { + byte[] bytes = name.startsWith('org.grails.plugin.cache.') ? null : classes[name] + if (bytes == null) { + throw new ClassNotFoundException(name) + } + defineClass(name, bytes, 0, bytes.length) + } + } + loader.loadClass(className) + } + private Map run(Map row, Class probe) { Map instances = [:] List created = [] diff --git a/grails-cache/src/test/resources/org/grails/plugin/cache/GrailsCacheManagerAware-8.0.0.groovy.txt b/grails-cache/src/test/resources/org/grails/plugin/cache/GrailsCacheManagerAware-8.0.0.groovy.txt new file mode 100644 index 00000000000..932c5f093f4 --- /dev/null +++ b/grails-cache/src/test/resources/org/grails/plugin/cache/GrailsCacheManagerAware-8.0.0.groovy.txt @@ -0,0 +1,58 @@ +/* + * 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 groovy.transform.CompileStatic + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.cache.CacheManager + +import grails.plugin.cache.CustomCacheKeyGenerator +import grails.plugin.cache.GrailsCacheKeyGenerator + +/** + * A trait for classes that are cache aware + * + * @since 4.0 + * @author Graeme Rocher + */ +@CompileStatic +trait GrailsCacheManagerAware { + + @Autowired(required = false) + private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() + + @Autowired(required = false) + private CacheManager grailsCacheManager + + /** + * @return The Grails cache manager or null if it isn't present + */ + CacheManager getGrailsCacheManager() { + return grailsCacheManager + } + + /** + * @return The custom key generator, or null if it isn't present + */ + GrailsCacheKeyGenerator getCustomCacheKeyGenerator() { + return customCacheKeyGenerator + } +} diff --git a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc index 6b711519930..067e3130ccf 100644 --- a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc +++ b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc @@ -20,3 +20,7 @@ under the License. The plugin registers an instance of the link:{springapi}/org/springframework/cache/CacheManager.html[CacheManager] interface as the `grailsCacheManager` Spring bean, so it's easy to access using dependency injection. The most common method you would call on the `grailsCacheManager` is `getCache(String name)` to access a link:{springapi}/org/springframework/cache/Cache.html[Cache] instance programmatically. This shouldn't be needed often however. From the `Cache` instance you can also access the underlying cache implementation using `cache.getNativeCache()`. + +The cache annotations and the cache tags cache with the `grailsCacheManager` bean. A cache provider plugin replaces it by defining a bean of that name, and an application can do the same with a `GrailsCacheManager` of its own. Another cache manager in the application context does not change which one is used, even when it is marked primary. That might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. Grails logs once, at INFO level, that it passed a primary one over. + +With caching turned off (`grails.cache.enabled: false`) there is no `grailsCacheManager`, and the annotations cache with the cache manager Spring would inject: the only one in the context, or the one marked primary. Where there are several and none is primary, they do not cache, and a warning names the cache managers. diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index 2ef92f4adab..201aebc1ec4 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -4972,3 +4972,15 @@ As of Grails 8.0.1, an exception an action throws is recorded as an error on the * Whether case matters follows the database: Oracle, H2 and Db2 match case-sensitively, and MySQL and MariaDB by the collation of the column. PostgreSQL matches with `~` (case-sensitive) with Hibernate 7 and `~*` (case-insensitive) with Hibernate 5; see issue 16882. See the `rlike` entry of the criteria reference for the databases that match with a regular expression. + +==== 94. Cache Annotations Use `grailsCacheManager` When Another Cache Manager Is Defined + +Grails 8.0.0 injected the cache manager the cache annotations use by type. An application context with a second `CacheManager` beside the plugin's `grailsCacheManager` therefore failed to start unless one of them was marked primary, and that is what happens when the Spring Security plugin's `cacheUsers` is set. Grails now chooses the cache manager this way: + +* The bean named `grailsCacheManager` comes first. +* Where there is none, as when `grails.cache.enabled` is `false`, it is the cache manager Spring would inject: the only one, or the one marked primary. +* Where Spring cannot choose one, the class does not cache, and a warning names the cache managers. Grails 8.0.0 failed to start in that case. + +In an application that marked a cache manager of its own primary, next to `grailsCacheManager`, the cache annotations used that cache manager. They now use `grailsCacheManager`, and Grails logs once, at INFO level, that it passed the primary one over. To keep caching with another cache manager, define it as the `grailsCacheManager` bean. It has to implement `GrailsCacheManager`, as the cache tags and the plugin's startup use it too. + +A plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until it is compiled against a later version. From bf0feaabefdb594428285d9ba001082b1fff1ce3 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 20:20:25 -0800 Subject: [PATCH 07/20] Fail on an inactive scope, inject in a bare bean factory, report priority too The cache manager was taken with getIfAvailable, which answers null for a scoped cache manager whose scope is not active, where the injection failed the bean; it is now taken with getObject, with none and Spring not choosing handled as before. The bean factory is taken through a provider, as a bean factory that is not an application context does not inject itself, and Spring skipped the method there, leaving no cache manager where the field was injected. The report of a cache manager passed over for grailsCacheManager now counts one Spring prefers by priority as well as primary, looks in parent contexts, leaves out beans Spring would not inject, and scans once for each bean factory. The guide says the plugin, not the application, defines no grailsCacheManager with caching off, and section 94 says that a plugin compiled against 8.0.0 still fails beside a second cache manager until it is recompiled, and that one compiled against this version needs it at runtime. --- .../cache/GrailsCacheManagerAware.groovy | 7 +- .../cache/GrailsCacheManagerLookup.groovy | 67 ++++++--- .../cache/CacheAutoConfigurationSpec.groovy | 2 +- .../GrailsCacheManagerLookupMatrixSpec.groovy | 133 +++++++++++++++--- .../guide/cache/cacheUsage/cacheManager.adoc | 4 +- .../src/en/guide/upgrading/upgrading80x.adoc | 8 +- 6 files changed, 171 insertions(+), 50 deletions(-) diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index a787e78a4f4..d22fcefb733 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -55,12 +55,13 @@ trait GrailsCacheManagerAware { * as Spring falls back to matching the field's name and a trait's field is renamed in the class * that implements it. See {@link GrailsCacheManagerLookup} for which cache manager is chosen. * - * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up + * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up; a + * provider, as a bean factory that is not an application context does not inject itself * @param cacheManagers the cache manager Spring would inject, where there is none of that name */ @Autowired(required = false) - void injectGrailsCacheManager(BeanFactory beanFactory, ObjectProvider cacheManagers) { - grailsCacheManager = GrailsCacheManagerLookup.find(beanFactory, cacheManagers, getClass()) + void injectGrailsCacheManager(ObjectProvider beanFactory, ObjectProvider cacheManagers) { + grailsCacheManager = GrailsCacheManagerLookup.find(beanFactory.getIfAvailable(), cacheManagers, getClass()) } /** diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy index 5978114692f..b0f1ea715ef 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy @@ -22,24 +22,29 @@ import groovy.transform.CompileStatic import groovy.util.logging.Slf4j import org.springframework.beans.factory.BeanFactory +import org.springframework.beans.factory.BeanFactoryUtils +import org.springframework.beans.factory.NoSuchBeanDefinitionException import org.springframework.beans.factory.NoUniqueBeanDefinitionException import org.springframework.beans.factory.ObjectProvider +import org.springframework.beans.factory.config.BeanDefinition import org.springframework.beans.factory.config.ConfigurableListableBeanFactory +import org.springframework.beans.factory.support.AbstractBeanDefinition import org.springframework.cache.CacheManager +import org.springframework.core.annotation.OrderUtils /** * Chooses the cache manager a {@link GrailsCacheManagerAware} class caches with, when Spring creates * it. * *

The bean named {@code grailsCacheManager} comes first, as the plugin creates its caches in it - * and its tag library is wired to it by name; a cache manager marked primary is passed over for it, - * which is logged once. Without one, the cache manager is the one Spring resolves for the - * {@code ObjectProvider} it is given, which is the one it injected into the trait's - * {@code @Autowired(required = false)} field: the only candidate, or the one marked primary or of the - * highest priority, with lazy beans, fallback beans and beans that are not autowire candidates - * treated as that injection treated them, and only the cache manager chosen created. Where Spring - * cannot choose, which failed startup when the field was injected, there is no cache manager, and a - * warning says why.

+ * and its tag library is wired to it by name. A cache manager Spring would have preferred, as primary + * or by priority, is passed over for it, which is logged once for each bean factory. Without one of + * that name, the cache manager is the one Spring resolves for the {@code ObjectProvider} it is given, + * which is how it resolved the trait's {@code @Autowired(required = false)} field: the only + * candidate, or the one marked primary or of the highest priority, with lazy beans, fallback beans, + * beans that are not autowire candidates and scoped beans treated as that injection treated them, + * and only the cache manager chosen created. Where Spring cannot choose, which failed startup when + * the field was injected, there is no cache manager, and a warning gives Spring's reason.

* * @since 8.0.1 */ @@ -49,7 +54,7 @@ final class GrailsCacheManagerLookup { static final String BEAN_NAME = 'grailsCacheManager' - /** The bean factories a primary cache manager passed over has been reported for. */ + /** The bean factories a preferred cache manager passed over has been reported for. */ private static final Set REPORTED = Collections.synchronizedSet( Collections.newSetFromMap(new WeakHashMap())) @@ -57,38 +62,58 @@ final class GrailsCacheManagerLookup { } /** - * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up + * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up, or null + * where there is none to look it up in * @param cacheManagers the cache manager Spring would inject * @param owner the class that caches with it, which a warning names * @return the cache manager, or null if there is none or Spring cannot choose one */ static CacheManager find(BeanFactory beanFactory, ObjectProvider cacheManagers, Class owner) { - if (beanFactory.containsBean(BEAN_NAME) && beanFactory.isTypeMatch(BEAN_NAME, CacheManager)) { - reportPrimaryPassedOver(beanFactory) + if (beanFactory != null && beanFactory.containsBean(BEAN_NAME) && beanFactory.isTypeMatch(BEAN_NAME, CacheManager)) { + reportPreferredPassedOver(beanFactory) return beanFactory.getBean(BEAN_NAME, CacheManager) } try { - return cacheManagers.getIfAvailable() + // getObject rather than getIfAvailable, which would answer null for a scoped cache manager + // whose scope is not active, where the injection failed + return cacheManagers.getObject() } catch (NoUniqueBeanDefinitionException e) { log.warn('{} does not cache: there is no cache manager named {}, and Spring cannot choose one. {} ' + 'Define the one to cache with as {}.', owner.name, BEAN_NAME, e.message, BEAN_NAME) return null } + catch (NoSuchBeanDefinitionException ignored) { + return null + } } - private static void reportPrimaryPassedOver(BeanFactory beanFactory) { - if (!log.infoEnabled || !(beanFactory instanceof ConfigurableListableBeanFactory)) { + private static void reportPreferredPassedOver(BeanFactory beanFactory) { + if (!log.infoEnabled || !(beanFactory instanceof ConfigurableListableBeanFactory) || REPORTED.contains(beanFactory)) { return } ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) beanFactory - List primary = listable.getBeanNamesForType(CacheManager, true, false).findAll { String name -> - name != BEAN_NAME && !(BEAN_NAME in listable.getAliases(name)) && - listable.containsBeanDefinition(name) && listable.getBeanDefinition(name).primary + List preferred = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(listable, CacheManager, true, false) + .findAll { String name -> + name != BEAN_NAME && !(BEAN_NAME in listable.getAliases(name)) && preferredBySpring(listable, name) + } + if (REPORTED.add(beanFactory) && preferred) { + log.info('Grails caches with the cache manager named {}, not with {}, which Spring prefers as primary or ' + + 'by priority. Define the one to cache with as {}.', BEAN_NAME, preferred.join(', '), BEAN_NAME) + } + } + + /** Whether Spring would have preferred the cache manager when injecting one by type. */ + private static boolean preferredBySpring(ConfigurableListableBeanFactory beanFactory, String name) { + BeanDefinition definition = beanFactory.getMergedBeanDefinition(name) + if (!definition.autowireCandidate || + (definition instanceof AbstractBeanDefinition && !((AbstractBeanDefinition) definition).defaultCandidate)) { + return false } - if (primary && REPORTED.add(beanFactory)) { - log.info('Grails caches with the cache manager named {}, not with {}, which is marked primary. ' + - 'Define the one to cache with as {}.', BEAN_NAME, primary.join(', '), BEAN_NAME) + if (definition.primary) { + return true } + Class type = beanFactory.getType(name, false) + type != null && OrderUtils.getPriority(type) != null } } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 4a92f574899..b8ecf99aee3 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -214,7 +214,7 @@ class CacheAutoConfigurationSpec extends Specification { } void 'a lazy cache manager is not created to find the Grails one'() { - given: 'a lazy cache manager whose store is down, which the injection this replaced never created' + given: 'a lazy cache manager whose store is down, beside the plugin\'s' AnnotationConfigApplicationContext context = buildContext([:], null, [:], null, [unreachableCacheManager: STORE_DOWN]) expect: 'the context starts, and the Grails cache manager is used' diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy index ae0cbecd0ce..3349771d38a 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy @@ -23,27 +23,35 @@ import java.util.function.Supplier import jakarta.annotation.Priority import ch.qos.logback.classic.Level +import org.codehaus.groovy.control.CompilationUnit +import org.codehaus.groovy.control.CompilerConfiguration +import org.codehaus.groovy.tools.GroovyClass import org.springframework.beans.BeansException +import org.springframework.beans.factory.ObjectFactory import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor import org.springframework.beans.factory.config.BeanDefinition import org.springframework.beans.factory.config.BeanDefinitionCustomizer +import org.springframework.beans.factory.config.Scope import org.springframework.beans.factory.support.AbstractBeanDefinition +import org.springframework.beans.factory.support.DefaultListableBeanFactory +import org.springframework.beans.factory.support.RootBeanDefinition +import org.springframework.beans.factory.support.ScopeNotActiveException import org.springframework.cache.CacheManager import org.springframework.cache.concurrent.ConcurrentMapCacheManager import org.springframework.context.annotation.AnnotationConfigUtils import org.springframework.context.support.GenericApplicationContext -import org.codehaus.groovy.control.CompilationUnit -import org.codehaus.groovy.control.CompilerConfiguration -import org.codehaus.groovy.tools.GroovyClass import spock.lang.Shared import spock.lang.Specification import org.apache.grails.core.testing.support.LogCapture /** - * Which cache manager a cache-aware class gets, for every arrangement of cache managers, against the - * oracle of what Spring injected into the trait's {@code @Autowired(required = false) CacheManager} - * field before it looked the cache manager up. + * Which cache manager a cache-aware class gets, against the oracle of what Spring injected into the + * trait's {@code @Autowired(required = false) CacheManager} field before the trait chose it itself. + * The matrix crosses the ways a bean named {@code grailsCacheManager} can be defined with none, one + * or two other cache managers, each defined in one of the ways a bean is chosen or passed over for + * injection, all in one context; the features after it cover the arrangements it does not. * *

The deliberate differences: a cache manager named {@code grailsCacheManager} is used whenever * there is one, as the plugin and its tag library use it by name; and where Spring cannot choose, which @@ -141,13 +149,98 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { then: log.events*.formattedMessage == ['Grails caches with the cache manager named grailsCacheManager, not with redis, ' + - 'which is marked primary. Define the one to cache with as grailsCacheManager.'] + 'which Spring prefers as primary or by priority. Define the one to cache with as grailsCacheManager.'] cleanup: log?.close() context?.close() } + void 'a cache manager passed over that Spring prefers by priority, or that is primary in a parent context, is reported'() { + given: + GenericApplicationContext parent = context([redis: 'primary'], [:]) + GenericApplicationContext child = context([grailsCacheManager: 'plain', hazelcast: 'priority'], [:], [], CacheAware, parent) + LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) + + when: + child.getBean('probe', CacheAware).grailsCacheManager + + then: + log.events.size() == 1 + log.events[0].formattedMessage.contains('not with hazelcast, redis,') + + cleanup: + log?.close() + child?.close() + parent?.close() + } + + void 'a primary cache manager that Spring would not inject is not reported as passed over'() { + given: 'one excluded from injection, and one that is not a default candidate' + GenericApplicationContext context = context( + [grailsCacheManager: 'plain', first: 'primary+notCandidate', second: 'primary+notDefault'], [:]) + LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) + + when: + context.getBean('probe', CacheAware).grailsCacheManager + + then: + log.events == [] + + cleanup: + log?.close() + context?.close() + } + + void 'in a bean factory that is not an application context, the cache manager is still the one Spring injects'() { + given: 'a bare bean factory, which does not inject itself, processing @Autowired' + DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory() + beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor(beanFactory: beanFactory)) + CacheManager only = new ConcurrentMapCacheManager() + beanFactory.registerSingleton('cacheManager', only) + beanFactory.registerBeanDefinition('probe', new RootBeanDefinition(CacheAware)) + + expect: + beanFactory.getBean('probe', CacheAware).grailsCacheManager.is(only) + } + + void 'a cache manager whose scope is not active fails the bean, as its injection did'() { + given: 'the only cache manager, in a scope with no active instance, with no proxy' + GenericApplicationContext context = new GenericApplicationContext() + AnnotationConfigUtils.registerAnnotationConfigProcessors(context) + context.beanFactory.registerScope('inactive', new Scope() { + Object get(String name, ObjectFactory factory) { + throw new ScopeNotActiveException(name, 'inactive', new IllegalStateException('no active instance')) + } + Object remove(String name) { null } + void registerDestructionCallback(String name, Runnable callback) { } + Object resolveContextualObject(String key) { null } + String getConversationId() { null } + }) + BeanDefinitionCustomizer inactive = { BeanDefinition definition -> definition.scope = 'inactive' } as BeanDefinitionCustomizer + context.registerBean('cacheManager', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier, inactive) + BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer + context.registerBean('injected', Injected, lazy) + context.registerBean('probe', CacheAware, lazy) + context.refresh() + + when: + context.getBean('injected') + + then: 'the oracle' + thrown(BeansException) + + when: + context.getBean('probe') + + then: + BeansException e = thrown() + e.mostSpecificCause instanceof IllegalStateException + + cleanup: + context?.close() + } + void 'no primary cache manager is reported where grailsCacheManager is an alias of the primary one'() { given: 'the primary cache manager, under another name, aliased as grailsCacheManager' GenericApplicationContext context = context([redis: 'primary'], [:]) @@ -166,16 +259,14 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { } void 'the cache manager is chosen when the bean is created, as an injected one was'() { - given: 'a context with no cache manager' + given: 'a bean created in a context with no cache manager' GenericApplicationContext context = context([:], [:]) CacheAware aware = context.getBean('probe', CacheAware) - when: 'one is defined after the first lookup' - CacheManager first = aware.grailsCacheManager + when: 'one is defined before the bean is first asked for its cache manager' context.registerBean('later', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) - then: 'it would be found, but the lookup is not made again' - first == null + then: 'it would be found, but the choice was made when the bean was created' context.getBean('later') instanceof CacheManager aware.grailsCacheManager == null @@ -255,15 +346,17 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { } private GenericApplicationContext context(Map row, Map instances, - List created = [], Class probe = CacheAware) { - GenericApplicationContext context = new GenericApplicationContext() + List created = [], Class probe = CacheAware, + GenericApplicationContext parent = null) { + GenericApplicationContext context = new GenericApplicationContext(parent) AnnotationConfigUtils.registerAnnotationConfigProcessors(context) row.each { String name, String kind -> if (kind == 'wrongType') { context.registerBean(name, String, { -> 'not a cache manager' } as Supplier) return } - Class type = kind == 'priority' ? HighPriorityCacheManager : ConcurrentMapCacheManager + Set attributes = kind.split(/\+/) as Set + Class type = 'priority' in attributes ? HighPriorityCacheManager : ConcurrentMapCacheManager Supplier supplier = { -> created << name CacheManager instance = type.getDeclaredConstructor().newInstance() @@ -272,11 +365,11 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { } as Supplier BeanDefinitionCustomizer customizer = { BeanDefinition definition -> AbstractBeanDefinition bean = (AbstractBeanDefinition) definition - bean.primary = kind == 'primary' - bean.lazyInit = kind == 'lazy' - bean.autowireCandidate = kind != 'notCandidate' - bean.fallback = kind == 'fallback' - bean.defaultCandidate = kind != 'notDefault' + bean.primary = 'primary' in attributes + bean.lazyInit = 'lazy' in attributes + bean.autowireCandidate = !('notCandidate' in attributes) + bean.fallback = 'fallback' in attributes + bean.defaultCandidate = !('notDefault' in attributes) } as BeanDefinitionCustomizer context.registerBean(name, (Class) type, supplier, customizer) } diff --git a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc index 067e3130ccf..337a8d546e2 100644 --- a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc +++ b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc @@ -21,6 +21,6 @@ The plugin registers an instance of the link:{springapi}/org/springframework/cac The most common method you would call on the `grailsCacheManager` is `getCache(String name)` to access a link:{springapi}/org/springframework/cache/Cache.html[Cache] instance programmatically. This shouldn't be needed often however. From the `Cache` instance you can also access the underlying cache implementation using `cache.getNativeCache()`. -The cache annotations and the cache tags cache with the `grailsCacheManager` bean. A cache provider plugin replaces it by defining a bean of that name, and an application can do the same with a `GrailsCacheManager` of its own. Another cache manager in the application context does not change which one is used, even when it is marked primary. That might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. Grails logs once, at INFO level, that it passed a primary one over. +The cache annotations and the cache tags cache with the `grailsCacheManager` bean. A cache provider plugin replaces it by defining a bean of that name, and an application can do the same with a `GrailsCacheManager` of its own. Another cache manager in the application context does not change which one is used, even when Spring would prefer it, as primary or by priority. That might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. Grails logs once, at INFO level, that it passed a preferred one over. -With caching turned off (`grails.cache.enabled: false`) there is no `grailsCacheManager`, and the annotations cache with the cache manager Spring would inject: the only one in the context, or the one marked primary. Where there are several and none is primary, they do not cache, and a warning names the cache managers. +With caching turned off (`grails.cache.enabled: false`), the plugin defines no `grailsCacheManager`. Unless the application defines one, the annotations cache with the cache manager Spring would inject, such as the only one in the context or the one marked primary. Where Spring cannot choose one, they do not cache, and a warning gives Spring's reason. diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index 201aebc1ec4..a9525febd03 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -4979,8 +4979,10 @@ Grails 8.0.0 injected the cache manager the cache annotations use by type. An ap * The bean named `grailsCacheManager` comes first. * Where there is none, as when `grails.cache.enabled` is `false`, it is the cache manager Spring would inject: the only one, or the one marked primary. -* Where Spring cannot choose one, the class does not cache, and a warning names the cache managers. Grails 8.0.0 failed to start in that case. +* Where Spring cannot choose one, the class does not cache, and a warning gives Spring's reason. Grails 8.0.0 failed to start in that case. -In an application that marked a cache manager of its own primary, next to `grailsCacheManager`, the cache annotations used that cache manager. They now use `grailsCacheManager`, and Grails logs once, at INFO level, that it passed the primary one over. To keep caching with another cache manager, define it as the `grailsCacheManager` bean. It has to implement `GrailsCacheManager`, as the cache tags and the plugin's startup use it too. +In an application that marked a cache manager of its own primary, or gave it a priority, next to `grailsCacheManager`, the cache annotations used that cache manager. They now use `grailsCacheManager`, and Grails logs once, at INFO level, that it passed the preferred one over. To keep caching with another cache manager, define it as the `grailsCacheManager` bean. It has to implement `GrailsCacheManager`, as the cache tags and the plugin's startup use it too. -A plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until it is compiled against a later version. +A cached class in a plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until the plugin is compiled against a later version. Until then, next to a second cache manager, such as the one `cacheUsers` defines, that class still fails startup as it did with 8.0.0. + +The other way round, a plugin with cached classes compiled against this version needs it at runtime too: on Grails 8.0.0 those classes fail to start, as they call a method of the cache plugin that 8.0.0 does not have. Such a plugin declares `grailsVersion = '8.0.1 > *'`. From 12b57c288f05d78e54d9b22cde9f6d1bb56729a9 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 20:29:33 -0800 Subject: [PATCH 08/20] Never fail a bean over the report, and name the parameters as no bean is The report of a cache manager passed over read the bean definition of every cache manager, and one registered as a singleton has none, so the lookup threw and every cache-aware bean failed while INFO was enabled. A cache manager without a definition is now judged by the priority of its class, as Spring judges it, the factory is marked as reported before the scan, and anything the scan meets is logged at DEBUG level instead of failing the bean. Where Spring cannot otherwise choose, it takes the bean named like the parameter, which the trait's renamed field never matched. The injection method's parameters are now named as no bean would be; with the earlier names, a cache manager named cacheManagers was chosen where Spring otherwise could not choose. The spec compiles its class keeping parameter names, as the Grails Gradle plugin compiles an application. Section 94 says that grailsVersion makes Grails warn rather than stop, and that an 8.0.0 plugin's cached class fails beside a second cache manager unless one of them is primary. --- .../cache/GrailsCacheManagerAware.groovy | 17 ++++-- .../cache/GrailsCacheManagerLookup.groovy | 58 +++++++++++++------ .../GrailsCacheManagerLookupMatrixSpec.groovy | 49 ++++++++++++++++ .../src/en/guide/upgrading/upgrading80x.adoc | 4 +- 4 files changed, 103 insertions(+), 25 deletions(-) diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index d22fcefb733..c3b35ed862b 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -55,13 +55,20 @@ trait GrailsCacheManagerAware { * as Spring falls back to matching the field's name and a trait's field is renamed in the class * that implements it. See {@link GrailsCacheManagerLookup} for which cache manager is chosen. * - * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up; a - * provider, as a bean factory that is not an application context does not inject itself - * @param cacheManagers the cache manager Spring would inject, where there is none of that name + *

Where Spring cannot otherwise choose, it takes the bean named like the parameter, which the + * trait's renamed field never matched, so the parameters are named as no bean would be.

+ * + * @param grailsCacheManagerLookupBeanFactory where the cache manager named {@code grailsCacheManager} + * is looked up; a provider, as a bean factory that is not an application context does not inject + * itself + * @param grailsCacheManagerLookupCandidates the cache manager Spring would inject, where there is + * none of that name */ @Autowired(required = false) - void injectGrailsCacheManager(ObjectProvider beanFactory, ObjectProvider cacheManagers) { - grailsCacheManager = GrailsCacheManagerLookup.find(beanFactory.getIfAvailable(), cacheManagers, getClass()) + void injectGrailsCacheManager(ObjectProvider grailsCacheManagerLookupBeanFactory, + ObjectProvider grailsCacheManagerLookupCandidates) { + grailsCacheManager = GrailsCacheManagerLookup.find(grailsCacheManagerLookupBeanFactory.getIfAvailable(), + grailsCacheManagerLookupCandidates, getClass()) } /** diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy index b0f1ea715ef..caa5de454ab 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy @@ -21,6 +21,7 @@ package org.grails.plugin.cache import groovy.transform.CompileStatic import groovy.util.logging.Slf4j +import org.springframework.beans.BeansException import org.springframework.beans.factory.BeanFactory import org.springframework.beans.factory.BeanFactoryUtils import org.springframework.beans.factory.NoSuchBeanDefinitionException @@ -38,7 +39,8 @@ import org.springframework.core.annotation.OrderUtils * *

The bean named {@code grailsCacheManager} comes first, as the plugin creates its caches in it * and its tag library is wired to it by name. A cache manager Spring would have preferred, as primary - * or by priority, is passed over for it, which is logged once for each bean factory. Without one of + * or by priority, is passed over for it, which is logged once for each bean factory; the check never + * fails the bean. Without one of * that name, the cache manager is the one Spring resolves for the {@code ObjectProvider} it is given, * which is how it resolved the trait's {@code @Autowired(required = false)} field: the only * candidate, or the one marked primary or of the highest priority, with lazy beans, fallback beans, @@ -88,32 +90,52 @@ final class GrailsCacheManagerLookup { } } + /** Only reports, so that nothing it meets fails the bean it is reported for. */ private static void reportPreferredPassedOver(BeanFactory beanFactory) { - if (!log.infoEnabled || !(beanFactory instanceof ConfigurableListableBeanFactory) || REPORTED.contains(beanFactory)) { + if (!log.infoEnabled || !(beanFactory instanceof ConfigurableListableBeanFactory) || !REPORTED.add(beanFactory)) { return } - ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) beanFactory - List preferred = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(listable, CacheManager, true, false) - .findAll { String name -> - name != BEAN_NAME && !(BEAN_NAME in listable.getAliases(name)) && preferredBySpring(listable, name) - } - if (REPORTED.add(beanFactory) && preferred) { - log.info('Grails caches with the cache manager named {}, not with {}, which Spring prefers as primary or ' + - 'by priority. Define the one to cache with as {}.', BEAN_NAME, preferred.join(', '), BEAN_NAME) + try { + ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) beanFactory + List preferred = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(listable, CacheManager, true, false) + .findAll { String name -> + name != BEAN_NAME && !(BEAN_NAME in listable.getAliases(name)) && preferredBySpring(listable, name) + } + if (preferred) { + log.info('Grails caches with the cache manager named {}, not with {}, which Spring prefers as primary or ' + + 'by priority. Define the one to cache with as {}.', BEAN_NAME, preferred.join(', '), BEAN_NAME) + } + } + catch (BeansException e) { + log.debug('Could not tell whether a cache manager Spring prefers was passed over for {}', BEAN_NAME, e) } } - /** Whether Spring would have preferred the cache manager when injecting one by type. */ + /** + * Whether Spring would have preferred the cache manager when injecting one by type. A cache + * manager registered as a singleton has no bean definition, and only the priority of its class. + */ private static boolean preferredBySpring(ConfigurableListableBeanFactory beanFactory, String name) { - BeanDefinition definition = beanFactory.getMergedBeanDefinition(name) - if (!definition.autowireCandidate || - (definition instanceof AbstractBeanDefinition && !((AbstractBeanDefinition) definition).defaultCandidate)) { - return false - } - if (definition.primary) { - return true + BeanDefinition definition = definitionOf(beanFactory, name) + if (definition != null) { + if (!definition.autowireCandidate || + (definition instanceof AbstractBeanDefinition && !((AbstractBeanDefinition) definition).defaultCandidate)) { + return false + } + if (definition.primary) { + return true + } } Class type = beanFactory.getType(name, false) type != null && OrderUtils.getPriority(type) != null } + + private static BeanDefinition definitionOf(ConfigurableListableBeanFactory beanFactory, String name) { + try { + beanFactory.getMergedBeanDefinition(name) + } + catch (NoSuchBeanDefinitionException ignored) { + null + } + } } diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy index 3349771d38a..c656f766776 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy @@ -175,6 +175,45 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { parent?.close() } + void 'a cache manager registered as a singleton beside grailsCacheManager is reported by its priority, and fails nothing'() { + given: 'cache managers with no bean definition, one of a class with a priority' + GenericApplicationContext context = context([grailsCacheManager: 'plain'], [:]) + context.beanFactory.registerSingleton('plainSingleton', new ConcurrentMapCacheManager()) + context.beanFactory.registerSingleton('prioritySingleton', new HighPriorityCacheManager()) + LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) + + when: + CacheManager found = context.getBean('probe', CacheAware).grailsCacheManager + + then: + found.is(context.getBean('grailsCacheManager')) + log.events*.formattedMessage == ['Grails caches with the cache manager named grailsCacheManager, not with ' + + 'prioritySingleton, which Spring prefers as primary or by priority. Define the one to cache with as grailsCacheManager.'] + + cleanup: + log?.close() + context?.close() + } + + void 'a cache manager is not chosen for being named like a parameter of the injection method'() { + given: 'a cache-aware class compiled keeping parameter names, as the Grails Gradle plugin compiles an application' + Class compiled = compiledWithParameterNames(''' + package names + class NamedCacheAware implements org.grails.plugin.cache.GrailsCacheManagerAware { + } + ''', 'names.NamedCacheAware') + + and: 'cache managers named as such a parameter might be, none primary, which Spring matches by name only then' + GenericApplicationContext context = context( + [cacheManagers: 'plain', cacheManager: 'plain', candidates: 'plain', beanFactory: 'plain'], [:], [], compiled) + + expect: 'none is chosen for its name, as none was for the field the trait had, whose name matched no bean' + context.getBean('probe').grailsCacheManager == null + + cleanup: + context?.close() + } + void 'a primary cache manager that Spring would not inject is not reported as passed over'() { given: 'one excluded from injection, and one that is not a default candidate' GenericApplicationContext context = context( @@ -300,6 +339,16 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { context?.close() } + /** Compiles the source against this trait, keeping parameter names, and loads it. */ + private Class compiledWithParameterNames(String source, String className) { + CompilerConfiguration configuration = new CompilerConfiguration() + configuration.parameters = true + new GroovyClassLoader(getClass().classLoader, configuration).with { + parseClass(source) + loadClass(className) + } + } + /** * Compiles the source with the trait as 8.0.0 shipped it, and loads only the class, so that the * trait it runs against is this one, as for a plugin compiled against 8.0.0. diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index a9525febd03..a85da997ab1 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -4983,6 +4983,6 @@ Grails 8.0.0 injected the cache manager the cache annotations use by type. An ap In an application that marked a cache manager of its own primary, or gave it a priority, next to `grailsCacheManager`, the cache annotations used that cache manager. They now use `grailsCacheManager`, and Grails logs once, at INFO level, that it passed the preferred one over. To keep caching with another cache manager, define it as the `grailsCacheManager` bean. It has to implement `GrailsCacheManager`, as the cache tags and the plugin's startup use it too. -A cached class in a plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until the plugin is compiled against a later version. Until then, next to a second cache manager, such as the one `cacheUsers` defines, that class still fails startup as it did with 8.0.0. +A cached class in a plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until the plugin is compiled against a later version. Until then, next to a second cache manager, such as the one `cacheUsers` defines, that class still fails startup as it did with 8.0.0, unless one of the two is marked primary. -The other way round, a plugin with cached classes compiled against this version needs it at runtime too: on Grails 8.0.0 those classes fail to start, as they call a method of the cache plugin that 8.0.0 does not have. Such a plugin declares `grailsVersion = '8.0.1 > *'`. +The other way round, a plugin with cached classes compiled against this version needs the cache plugin of this version at runtime too: with that of 8.0.0, Spring fails to create those classes as beans, as they call a method of the cache plugin that 8.0.0 does not have. Such a plugin declares `grailsVersion = '8.0.1 > *'`, so that Grails warns at startup when it runs on an earlier version. From 39d3d5e949d1bbe95c2d82b90a34ab9ec73a92d9 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 13 Nov 2026 20:31:57 -0800 Subject: [PATCH 09/20] Say what the report and the parameter names guard against exactly The report's comment claimed more than its catch covers, the parameter javadoc said a bean named like a parameter is taken only where Spring cannot otherwise choose, where it is taken over one of a higher priority too, and section 94 now counts a priority, as well as primary, as what lets an 8.0.0 plugin's cached class be created beside a second cache manager. --- .../org/grails/plugin/cache/GrailsCacheManagerAware.groovy | 4 ++-- .../org/grails/plugin/cache/GrailsCacheManagerLookup.groovy | 6 +++--- grails-doc/src/en/guide/upgrading/upgrading80x.adoc | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index c3b35ed862b..021c80405f0 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -55,8 +55,8 @@ trait GrailsCacheManagerAware { * as Spring falls back to matching the field's name and a trait's field is renamed in the class * that implements it. See {@link GrailsCacheManagerLookup} for which cache manager is chosen. * - *

Where Spring cannot otherwise choose, it takes the bean named like the parameter, which the - * trait's renamed field never matched, so the parameters are named as no bean would be.

+ *

Unless another cache manager is marked primary, Spring takes the one named like the parameter, + * which no bean was for the trait's renamed field, so the parameters are named as no bean would be.

* * @param grailsCacheManagerLookupBeanFactory where the cache manager named {@code grailsCacheManager} * is looked up; a provider, as a bean factory that is not an application context does not inject diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy index caa5de454ab..45bd17263a4 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy @@ -39,8 +39,8 @@ import org.springframework.core.annotation.OrderUtils * *

The bean named {@code grailsCacheManager} comes first, as the plugin creates its caches in it * and its tag library is wired to it by name. A cache manager Spring would have preferred, as primary - * or by priority, is passed over for it, which is logged once for each bean factory; the check never - * fails the bean. Without one of + * or by priority, is passed over for it, which is logged once for each bean factory; what the bean + * factory throws while it is checked fails nothing. Without one of * that name, the cache manager is the one Spring resolves for the {@code ObjectProvider} it is given, * which is how it resolved the trait's {@code @Autowired(required = false)} field: the only * candidate, or the one marked primary or of the highest priority, with lazy beans, fallback beans, @@ -90,7 +90,7 @@ final class GrailsCacheManagerLookup { } } - /** Only reports, so that nothing it meets fails the bean it is reported for. */ + /** Only reports: what the bean factory throws while it is asked fails nothing. */ private static void reportPreferredPassedOver(BeanFactory beanFactory) { if (!log.infoEnabled || !(beanFactory instanceof ConfigurableListableBeanFactory) || !REPORTED.add(beanFactory)) { return diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index a85da997ab1..bd026bb97d5 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -4983,6 +4983,6 @@ Grails 8.0.0 injected the cache manager the cache annotations use by type. An ap In an application that marked a cache manager of its own primary, or gave it a priority, next to `grailsCacheManager`, the cache annotations used that cache manager. They now use `grailsCacheManager`, and Grails logs once, at INFO level, that it passed the preferred one over. To keep caching with another cache manager, define it as the `grailsCacheManager` bean. It has to implement `GrailsCacheManager`, as the cache tags and the plugin's startup use it too. -A cached class in a plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until the plugin is compiled against a later version. Until then, next to a second cache manager, such as the one `cacheUsers` defines, that class still fails startup as it did with 8.0.0, unless one of the two is marked primary. +A cached class in a plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until the plugin is compiled against a later version. Until then, next to a second cache manager, such as the one `cacheUsers` defines, that class still fails to be created as it did with 8.0.0, unless one of the two is marked primary or has a priority. The other way round, a plugin with cached classes compiled against this version needs the cache plugin of this version at runtime too: with that of 8.0.0, Spring fails to create those classes as beans, as they call a method of the cache plugin that 8.0.0 does not have. Such a plugin declares `grailsVersion = '8.0.1 > *'`, so that Grails warns at startup when it runs on an earlier version. From fd973ec2569b542a663ab5c0ae4654c97a953cdb Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 07:26:24 -0800 Subject: [PATCH 10/20] Run a cached method uncached where its cache does not exist A cache manager answers null for a cache name it has no cache of, as JCacheCacheManager does for a cache it was not configured with, and the code the cache annotations generate called the cache without checking, so every call failed with a NullPointerException. That is what happened with caching off and the Spring Security plugin's cacheUsers cache manager the only one, and with any such cache manager as grailsCacheManager. What follows the cache lookup now runs only where there is a cache: a @Cacheable or @CachePut method otherwise runs as it does without a cache manager, and @CacheEvict has nothing to evict. GrailsCacheManagerLookup.reportMissingCache logs a warning naming the class and the cache once for each cache manager and name. Classes compiled against this version get it; those compiled against 8.0.1 already need 8.0.1 for the trait. MissingCacheSpec drives annotated classes, compiled statically and dynamically, against a cache manager with one named cache; with the previous generated code both fail with the NullPointerException. --- .../cache/GrailsCacheManagerLookup.groovy | 27 +++++ .../AbstractCacheTransformation.groovy | 32 +++++ .../compiler/CacheEvictTransformation.groovy | 9 +- .../compiler/CachePutTransformation.groovy | 9 +- .../compiler/CacheableTransformation.groovy | 11 +- .../plugin/cache/MissingCacheSpec.groovy | 109 ++++++++++++++++++ .../guide/cache/cacheUsage/cacheManager.adoc | 2 + .../src/en/guide/upgrading/upgrading80x.adoc | 2 + 8 files changed, 191 insertions(+), 10 deletions(-) create mode 100644 grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy index 45bd17263a4..ea8b0ef4862 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy @@ -18,6 +18,8 @@ */ package org.grails.plugin.cache +import java.util.concurrent.ConcurrentHashMap + import groovy.transform.CompileStatic import groovy.util.logging.Slf4j @@ -60,9 +62,34 @@ final class GrailsCacheManagerLookup { private static final Set REPORTED = Collections.synchronizedSet( Collections.newSetFromMap(new WeakHashMap())) + /** The names of the caches reported missing, for each cache manager. */ + private static final Map> MISSING = Collections.synchronizedMap( + new WeakHashMap>()) + private GrailsCacheManagerLookup() { } + /** + * Called by the code the cache annotations generate, where the cache manager has no cache of the + * name an annotation gives, as {@code JCacheCacheManager} has none it was not configured with. + * The method then runs as it does without a cache manager, and this says so once for each cache + * manager and name. + * + * @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 reportMissingCache(CacheManager cacheManager, String cacheName, Class owner) { + Set reported = MISSING.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, or define the one to cache with as {}.', + owner.name, cacheName, cacheManager.getClass().name, BEAN_NAME) + } + } + /** * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up, or null * where there is none to look it up in 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..5641d5fa3c8 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.GrailsCacheManagerLookup 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 CACHE_MANAGER_LOOKUP_CLASS_NODE = make(GrailsCacheManagerLookup) + private static final MethodNode REPORT_MISSING_CACHE_METHOD_NODE = CACHE_MANAGER_LOOKUP_CLASS_NODE.getMethod('reportMissingCache', + [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(CACHE_MANAGER_LOOKUP_CLASS_NODE), 'reportMissingCache', + 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/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy new file mode 100644 index 00000000000..b6d0cac61cf --- /dev/null +++ b/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy @@ -0,0 +1,109 @@ +/* + * 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 grails.plugin.cache + +import ch.qos.logback.classic.Level +import org.springframework.cache.CacheManager +import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import spock.lang.Specification +import spock.lang.Unroll + +import org.apache.grails.core.testing.support.LogCapture +import org.grails.plugin.cache.GrailsCacheManagerLookup + +/** + * A cache manager answers null for a cache name it has no cache of, as {@code JCacheCacheManager} + * does for a cache it was not configured with, and as the Spring Security plugin's cache manager does + * when caching is off and the annotations use it. The annotated methods then run uncached, rather than + * failing on the missing cache, and that is reported once for each cache manager and name. + */ +class MissingCacheSpec extends Specification { + + @Unroll + void 'a method whose cache the cache manager does not have runs uncached, compiled #mode'() { + given: 'a cache manager with only the cache named configured' + def service = compile(mode).getDeclaredConstructor().newInstance() + CacheManager cacheManager = new ConcurrentMapCacheManager('configured') + service.@"org_grails_plugin_cache_GrailsCacheManagerAware__grailsCacheManager" = cacheManager + LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.WARN) + + when: 'every annotation is used twice with a cache that is missing' + List results = [service.cached(1), service.cached(1), service.put(1), service.put(1)] + service.evict(1) + service.evict(1) + service.evictAll() + service.evictAll() + + then: 'each method ran every time, and answered as it does uncached' + results == [2, 2, 2, 2] + service.calls == 8 + + and: 'each missing cache is reported once' + log.events*.formattedMessage == [ + "CachedService does not cache with missing: its cache manager, ${ConcurrentMapCacheManager.name}, " + + 'has no cache of that name, so the methods run uncached. Configure the cache in that cache manager, ' + + 'or define the one to cache with as grailsCacheManager.', + "CachedService does not cache with gone: its cache manager, ${ConcurrentMapCacheManager.name}, " + + 'has no cache of that name, so the methods run uncached. Configure the cache in that cache manager, ' + + 'or define the one to cache with as grailsCacheManager.', + ] as List + + when: 'a cache the cache manager does have' + service.calls = 0 + List cached = [service.cachedWhereConfigured(1), service.cachedWhereConfigured(1)] + + then: 'still caches' + cached == [3, 3] + service.calls == 1 + + cleanup: + log?.close() + + where: + mode << ['statically', 'dynamically'] + } + + private static Class compile(String mode) { + new GroovyShell().evaluate(""" +import grails.plugin.cache.* +import groovy.transform.CompileStatic + +${mode == 'statically' ? '@CompileStatic' : ''} +class CachedService { + int calls + + @Cacheable('missing') + int cached(int x) { calls++; x * 2 } + + @Cacheable('configured') + int cachedWhereConfigured(int x) { calls++; x * 3 } + + @CachePut('missing') + int put(int x) { calls++; x * 2 } + + @CacheEvict('gone') + void evict(int x) { calls++ } + + @CacheEvict(value = 'gone', allEntries = true) + void evictAll() { calls++ } +} +return CachedService +""") as Class + } +} diff --git a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc index 337a8d546e2..79751b119f1 100644 --- a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc +++ b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc @@ -24,3 +24,5 @@ The most common method you would call on the `grailsCacheManager` is `getCache(S The cache annotations and the cache tags cache with the `grailsCacheManager` bean. A cache provider plugin replaces it by defining a bean of that name, and an application can do the same with a `GrailsCacheManager` of its own. Another cache manager in the application context does not change which one is used, even when Spring would prefer it, as primary or by priority. That might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. Grails logs once, at INFO level, that it passed a preferred one over. With caching turned off (`grails.cache.enabled: false`), the plugin defines no `grailsCacheManager`. Unless the application defines one, the annotations cache with the cache manager Spring would inject, such as the only one in the context or the one marked primary. Where Spring cannot choose one, they do not cache, and a warning gives Spring's reason. + +A cache manager may have no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with. The annotated method then runs uncached, and a warning names the class and the cache once for each cache manager. diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index bd026bb97d5..b7e690b2f4e 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -4981,6 +4981,8 @@ Grails 8.0.0 injected the cache manager the cache annotations use by type. An ap * Where there is none, as when `grails.cache.enabled` is `false`, it is the cache manager Spring would inject: the only one, or the one marked primary. * Where Spring cannot choose one, the class does not cache, and a warning gives Spring's reason. Grails 8.0.0 failed to start in that case. +Where the cache manager has no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with, the method now runs uncached, and a warning names the class and the cache once. Grails 8.0.0 failed with a `NullPointerException` on each call. This applies to classes compiled against this version. + In an application that marked a cache manager of its own primary, or gave it a priority, next to `grailsCacheManager`, the cache annotations used that cache manager. They now use `grailsCacheManager`, and Grails logs once, at INFO level, that it passed the preferred one over. To keep caching with another cache manager, define it as the `grailsCacheManager` bean. It has to implement `GrailsCacheManager`, as the cache tags and the plugin's startup use it too. A cached class in a plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until the plugin is compiled against a later version. Until then, next to a second cache manager, such as the one `cacheUsers` defines, that class still fails to be created as it did with 8.0.0, unless one of the two is marked primary or has a priority. From 134856bdf081cbf0833ba3e62c86df9baee680f2 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 07:27:13 -0800 Subject: [PATCH 11/20] Compile the 8.0.0 compatibility fixture without writing class files The compatibility feature compiled through the output phase, which wrote the 8.0.0 trait's and the fixture's class files into the module's working directory. It now stops at class generation and takes the classes from the compilation unit. --- .../plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy index c656f766776..83589030e8c 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy @@ -25,6 +25,7 @@ import jakarta.annotation.Priority import ch.qos.logback.classic.Level import org.codehaus.groovy.control.CompilationUnit import org.codehaus.groovy.control.CompilerConfiguration +import org.codehaus.groovy.control.Phases import org.codehaus.groovy.tools.GroovyClass import org.springframework.beans.BeansException import org.springframework.beans.factory.ObjectFactory @@ -358,7 +359,8 @@ class GrailsCacheManagerLookupMatrixSpec extends Specification { CompilationUnit unit = new CompilationUnit(new CompilerConfiguration(), null, new GroovyClassLoader(getClass().classLoader)) unit.addSource('GrailsCacheManagerAware.groovy', trait800) unit.addSource('OldCacheAware.groovy', source) - unit.compile() + // up to class generation only, so that nothing is written to the working directory + unit.compile(Phases.CLASS_GENERATION) Map classes = unit.classes.collectEntries { GroovyClass compiled -> [(compiled.name): compiled.bytes] } assert classes.keySet().any { it.startsWith('org.grails.plugin.cache.GrailsCacheManagerAware') } ClassLoader loader = new ClassLoader(getClass().classLoader) { From d5fd4e81e91e7c19766c3f2c4859526343829657 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Tue, 17 Nov 2026 07:41:25 -0800 Subject: [PATCH 12/20] Resolve the cache manager by an alias of grailsCacheManager instead The trait method chose grailsCacheManager over a cache manager Spring would have preferred, so an application that starts on 8.0.0 with a primary or @Priority cache manager of its own would move its caches in a patch release, and classes compiled against 8.0.0 still failed beside a second cache manager. The trait is 8.0.0's again. GrailsCacheManagerAliasRegistrar, a bean factory post-processor of the plugin's auto-configuration, gives the bean named grailsCacheManager the name the trait's field has in each class that implements it. Spring falls back to that name only where it cannot otherwise choose, so the cacheUsers case now gets grailsCacheManager, for classes compiled against 8.0.0 too, and a primary cache manager is still used. A @Priority cache manager beside grailsCacheManager is the one choice that changes. The missing-cache report moves to MissingCacheReporter. GrailsCacheManagerAliasMatrixSpec runs 342 arrangements against 8.0.0, the same class in the same context without the alias. MissingCacheSpec creates the annotated class as a bean beside a second cache manager and covers a key closure. The guide, section 94 and the Grails 8 upgrade skill describe it. --- .../cache/GrailsCacheManagerAware.groovy | 33 +- .../cache/GrailsCacheManagerLookup.groovy | 168 ------- .../plugin/cache/MissingCacheReporter.groovy | 62 +++ .../AbstractCacheTransformation.groovy | 8 +- .../plugin/cache/CacheGrailsPlugin.groovy | 5 + .../GrailsCacheManagerAliasRegistrar.groovy | 58 +++ .../cache/CacheAutoConfigurationSpec.groovy | 24 +- .../plugin/cache/MissingCacheSpec.groovy | 58 ++- .../GrailsCacheManagerAliasMatrixSpec.groovy | 176 +++++++ .../GrailsCacheManagerLookupMatrixSpec.groovy | 457 ------------------ .../GrailsCacheManagerAware-8.0.0.groovy.txt | 58 --- .../guide/cache/cacheUsage/cacheManager.adoc | 4 +- .../src/en/guide/upgrading/upgrading80x.adoc | 16 +- .../skills/grails-8-upgrade/SKILL.md | 6 + 14 files changed, 364 insertions(+), 769 deletions(-) delete mode 100644 grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy create mode 100644 grails-cache/src/ast/groovy/org/grails/plugin/cache/MissingCacheReporter.groovy create mode 100644 grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy create mode 100644 grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy delete mode 100644 grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy delete mode 100644 grails-cache/src/test/resources/org/grails/plugin/cache/GrailsCacheManagerAware-8.0.0.groovy.txt diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy index 021c80405f0..932c5f093f4 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerAware.groovy @@ -21,8 +21,6 @@ package org.grails.plugin.cache import groovy.transform.CompileStatic -import org.springframework.beans.factory.BeanFactory -import org.springframework.beans.factory.ObjectProvider import org.springframework.beans.factory.annotation.Autowired import org.springframework.cache.CacheManager @@ -41,38 +39,11 @@ trait GrailsCacheManagerAware { @Autowired(required = false) private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() - /** - * Set by {@link #injectGrailsCacheManager} rather than injected. The trait keeps exactly the fields - * it had, so that a class compiled against an earlier version, which declares them itself, works - * with this one. - */ - private CacheManager grailsCacheManager - - /** - * Called by Spring when the class is created as a bean, where the trait's field used to be - * injected: another cache manager, such as the one the Spring Security plugin caches users with - * when {@code cacheUsers} is set, made that injection ambiguous, and the context failed to start, - * as Spring falls back to matching the field's name and a trait's field is renamed in the class - * that implements it. See {@link GrailsCacheManagerLookup} for which cache manager is chosen. - * - *

Unless another cache manager is marked primary, Spring takes the one named like the parameter, - * which no bean was for the trait's renamed field, so the parameters are named as no bean would be.

- * - * @param grailsCacheManagerLookupBeanFactory where the cache manager named {@code grailsCacheManager} - * is looked up; a provider, as a bean factory that is not an application context does not inject - * itself - * @param grailsCacheManagerLookupCandidates the cache manager Spring would inject, where there is - * none of that name - */ @Autowired(required = false) - void injectGrailsCacheManager(ObjectProvider grailsCacheManagerLookupBeanFactory, - ObjectProvider grailsCacheManagerLookupCandidates) { - grailsCacheManager = GrailsCacheManagerLookup.find(grailsCacheManagerLookupBeanFactory.getIfAvailable(), - grailsCacheManagerLookupCandidates, getClass()) - } + private CacheManager grailsCacheManager /** - * @return The cache manager this class caches with, or null if it has none + * @return The Grails cache manager or null if it isn't present */ CacheManager getGrailsCacheManager() { return grailsCacheManager diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy deleted file mode 100644 index ea8b0ef4862..00000000000 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/GrailsCacheManagerLookup.groovy +++ /dev/null @@ -1,168 +0,0 @@ -/* - * 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.beans.BeansException -import org.springframework.beans.factory.BeanFactory -import org.springframework.beans.factory.BeanFactoryUtils -import org.springframework.beans.factory.NoSuchBeanDefinitionException -import org.springframework.beans.factory.NoUniqueBeanDefinitionException -import org.springframework.beans.factory.ObjectProvider -import org.springframework.beans.factory.config.BeanDefinition -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory -import org.springframework.beans.factory.support.AbstractBeanDefinition -import org.springframework.cache.CacheManager -import org.springframework.core.annotation.OrderUtils - -/** - * Chooses the cache manager a {@link GrailsCacheManagerAware} class caches with, when Spring creates - * it. - * - *

The bean named {@code grailsCacheManager} comes first, as the plugin creates its caches in it - * and its tag library is wired to it by name. A cache manager Spring would have preferred, as primary - * or by priority, is passed over for it, which is logged once for each bean factory; what the bean - * factory throws while it is checked fails nothing. Without one of - * that name, the cache manager is the one Spring resolves for the {@code ObjectProvider} it is given, - * which is how it resolved the trait's {@code @Autowired(required = false)} field: the only - * candidate, or the one marked primary or of the highest priority, with lazy beans, fallback beans, - * beans that are not autowire candidates and scoped beans treated as that injection treated them, - * and only the cache manager chosen created. Where Spring cannot choose, which failed startup when - * the field was injected, there is no cache manager, and a warning gives Spring's reason.

- * - * @since 8.0.1 - */ -@Slf4j -@CompileStatic -final class GrailsCacheManagerLookup { - - static final String BEAN_NAME = 'grailsCacheManager' - - /** The bean factories a preferred cache manager passed over has been reported for. */ - private static final Set REPORTED = Collections.synchronizedSet( - Collections.newSetFromMap(new WeakHashMap())) - - /** The names of the caches reported missing, for each cache manager. */ - private static final Map> MISSING = Collections.synchronizedMap( - new WeakHashMap>()) - - private GrailsCacheManagerLookup() { - } - - /** - * Called by the code the cache annotations generate, where the cache manager has no cache of the - * name an annotation gives, as {@code JCacheCacheManager} has none it was not configured with. - * The method then runs as it does without a cache manager, and this says so once for each cache - * manager and name. - * - * @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 reportMissingCache(CacheManager cacheManager, String cacheName, Class owner) { - Set reported = MISSING.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, or define the one to cache with as {}.', - owner.name, cacheName, cacheManager.getClass().name, BEAN_NAME) - } - } - - /** - * @param beanFactory where the cache manager named {@code grailsCacheManager} is looked up, or null - * where there is none to look it up in - * @param cacheManagers the cache manager Spring would inject - * @param owner the class that caches with it, which a warning names - * @return the cache manager, or null if there is none or Spring cannot choose one - */ - static CacheManager find(BeanFactory beanFactory, ObjectProvider cacheManagers, Class owner) { - if (beanFactory != null && beanFactory.containsBean(BEAN_NAME) && beanFactory.isTypeMatch(BEAN_NAME, CacheManager)) { - reportPreferredPassedOver(beanFactory) - return beanFactory.getBean(BEAN_NAME, CacheManager) - } - try { - // getObject rather than getIfAvailable, which would answer null for a scoped cache manager - // whose scope is not active, where the injection failed - return cacheManagers.getObject() - } - catch (NoUniqueBeanDefinitionException e) { - log.warn('{} does not cache: there is no cache manager named {}, and Spring cannot choose one. {} ' + - 'Define the one to cache with as {}.', owner.name, BEAN_NAME, e.message, BEAN_NAME) - return null - } - catch (NoSuchBeanDefinitionException ignored) { - return null - } - } - - /** Only reports: what the bean factory throws while it is asked fails nothing. */ - private static void reportPreferredPassedOver(BeanFactory beanFactory) { - if (!log.infoEnabled || !(beanFactory instanceof ConfigurableListableBeanFactory) || !REPORTED.add(beanFactory)) { - return - } - try { - ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) beanFactory - List preferred = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(listable, CacheManager, true, false) - .findAll { String name -> - name != BEAN_NAME && !(BEAN_NAME in listable.getAliases(name)) && preferredBySpring(listable, name) - } - if (preferred) { - log.info('Grails caches with the cache manager named {}, not with {}, which Spring prefers as primary or ' + - 'by priority. Define the one to cache with as {}.', BEAN_NAME, preferred.join(', '), BEAN_NAME) - } - } - catch (BeansException e) { - log.debug('Could not tell whether a cache manager Spring prefers was passed over for {}', BEAN_NAME, e) - } - } - - /** - * Whether Spring would have preferred the cache manager when injecting one by type. A cache - * manager registered as a singleton has no bean definition, and only the priority of its class. - */ - private static boolean preferredBySpring(ConfigurableListableBeanFactory beanFactory, String name) { - BeanDefinition definition = definitionOf(beanFactory, name) - if (definition != null) { - if (!definition.autowireCandidate || - (definition instanceof AbstractBeanDefinition && !((AbstractBeanDefinition) definition).defaultCandidate)) { - return false - } - if (definition.primary) { - return true - } - } - Class type = beanFactory.getType(name, false) - type != null && OrderUtils.getPriority(type) != null - } - - private static BeanDefinition definitionOf(ConfigurableListableBeanFactory beanFactory, String name) { - try { - beanFactory.getMergedBeanDefinition(name) - } - catch (NoSuchBeanDefinitionException ignored) { - null - } - } -} 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 5641d5fa3c8..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,7 +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.GrailsCacheManagerLookup +import org.grails.plugin.cache.MissingCacheReporter import static org.codehaus.groovy.ast.ClassHelper.CLOSURE_TYPE import static org.codehaus.groovy.ast.ClassHelper.MAP_TYPE @@ -107,8 +107,8 @@ 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 CACHE_MANAGER_LOOKUP_CLASS_NODE = make(GrailsCacheManagerLookup) - private static final MethodNode REPORT_MISSING_CACHE_METHOD_NODE = CACHE_MANAGER_LOOKUP_CLASS_NODE.getMethod('reportMissingCache', + 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[]) @@ -196,7 +196,7 @@ abstract class AbstractCacheTransformation extends AbstractMethodDecoratingTrans VariableExpression cacheVariableExpression, BlockStatement cacheBlock) { BlockStatement whereCacheExists = block() Object cacheName = ((ConstantExpression) annotationNode.getMember('value')).value - MethodCallExpression report = callX(classX(CACHE_MANAGER_LOOKUP_CLASS_NODE), 'reportMissingCache', + 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))) 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..202c5b5e74e 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.GrailsCacheManagerAliasRegistrar /** * 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(GrailsCacheManagerAliasRegistrar).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/GrailsCacheManagerAliasRegistrar.groovy b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy new file mode 100644 index 00000000000..c8cb64b0412 --- /dev/null +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy @@ -0,0 +1,58 @@ +/* + * 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 groovy.transform.CompileStatic + +import org.springframework.beans.BeansException +import org.springframework.beans.factory.config.BeanFactoryPostProcessor +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory + +/** + * Names the cache manager called {@code grailsCacheManager} after the field a cache-aware class has it + * injected into, so that Spring takes it where it cannot otherwise choose. + * + *

{@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. With this + * alias the renamed field matches {@code grailsCacheManager}. Where Spring could choose, which is the + * only cache manager or the one marked primary, nothing changes.

+ * + *

The alias is registered after every bean definition is in, so a {@code grailsCacheManager} that a + * cache provider plugin or the application defines gets it too, and it is registered only where there + * is a bean of that name and the alias is free.

+ * + * @since 8.0.1 + */ +@CompileStatic +class GrailsCacheManagerAliasRegistrar 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 ALIAS = "${GrailsCacheManagerAware.name.replace('.', '_')}__${CACHE_MANAGER_BEAN_NAME}".toString() + + @Override + void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + if (beanFactory.containsBean(CACHE_MANAGER_BEAN_NAME) && !beanFactory.containsBean(ALIAS)) { + beanFactory.registerAlias(CACHE_MANAGER_BEAN_NAME, ALIAS) + } + } +} diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index b8ecf99aee3..50b7d9946a4 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -175,18 +175,6 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } - void 'with caching disabled and several cache managers, none named grailsCacheManager, none is used'() { - given: - AnnotationConfigApplicationContext context = buildContext(['grails.cache.enabled': 'false'], null, - [cacheManager: new ConcurrentMapCacheManager(), otherCacheManager: new ConcurrentMapCacheManager()]) - - expect: 'the context still starts' - context.getBean(CacheAware).grailsCacheManager == null - - cleanup: - context.close() - } - void 'with caching disabled and several cache managers, the one marked primary is used, as Spring chose it before'() { given: CacheManager primary = new ConcurrentMapCacheManager() @@ -200,14 +188,14 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } - void 'the Grails cache manager is used over another cache manager marked primary'() { + void 'a cache manager marked primary beside the Grails one is still used, as in 8.0.0'() { given: 'an application\'s own cache manager, marked primary' - AnnotationConfigApplicationContext context = buildContext([:], null, - [cacheManager: new ConcurrentMapCacheManager()], 'cacheManager') + CacheManager primary = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext([:], null, [cacheManager: primary], 'cacheManager') - expect: 'the one the plugin creates its caches in, and its tag library uses' - context.getBean(CacheAware).grailsCacheManager.is(context.getBean('grailsCacheManager')) - context.getBean(GrailsCacheAdminService).grailsCacheManager.is(context.getBean('grailsCacheManager')) + expect: 'Spring chooses as it did; the name is only taken where it cannot' + context.getBean(CacheAware).grailsCacheManager.is(primary) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(primary) cleanup: context.close() diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy index b6d0cac61cf..0a876a6a4b7 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy @@ -18,62 +18,76 @@ */ package grails.plugin.cache +import java.util.function.Supplier + import ch.qos.logback.classic.Level import org.springframework.cache.CacheManager import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import org.springframework.context.annotation.AnnotationConfigUtils +import org.springframework.context.support.GenericApplicationContext import spock.lang.Specification import spock.lang.Unroll import org.apache.grails.core.testing.support.LogCapture -import org.grails.plugin.cache.GrailsCacheManagerLookup +import org.grails.plugin.cache.GrailsCacheManagerAliasRegistrar +import org.grails.plugin.cache.MissingCacheReporter /** * A cache manager answers null for a cache name it has no cache of, as {@code JCacheCacheManager} - * does for a cache it was not configured with, and as the Spring Security plugin's cache manager does - * when caching is off and the annotations use it. The annotated methods then run uncached, rather than + * does for a cache it was not configured with. The annotated methods then run uncached, rather than * failing on the missing cache, and that is reported once for each cache manager and name. */ class MissingCacheSpec extends Specification { @Unroll void 'a method whose cache the cache manager does not have runs uncached, compiled #mode'() { - given: 'a cache manager with only the cache named configured' - def service = compile(mode).getDeclaredConstructor().newInstance() + given: 'the annotated class created as a bean, beside a second cache manager, with grailsCacheManager having only the cache named configured' CacheManager cacheManager = new ConcurrentMapCacheManager('configured') - service.@"org_grails_plugin_cache_GrailsCacheManagerAware__grailsCacheManager" = cacheManager - LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.WARN) + GenericApplicationContext context = new GenericApplicationContext() + AnnotationConfigUtils.registerAnnotationConfigProcessors(context) + context.addBeanFactoryPostProcessor(new GrailsCacheManagerAliasRegistrar()) + context.registerBean('grailsCacheManager', CacheManager, { -> cacheManager } as Supplier) + context.registerBean('cacheManager', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) + context.registerBean('service', (Class) compile(mode)) + context.refresh() + def service = context.getBean('service') + LogCapture log = new LogCapture(MissingCacheReporter, Level.WARN) + + expect: 'it is injected with grailsCacheManager' + service.grailsCacheManager.is(cacheManager) when: 'every annotation is used twice with a cache that is missing' - List results = [service.cached(1), service.cached(1), service.put(1), service.put(1)] + List results = [service.cached(1), service.cached(1), service.cachedByKey(1), service.cachedByKey(1), + service.put(1), service.put(1)] service.evict(1) service.evict(1) service.evictAll() service.evictAll() then: 'each method ran every time, and answered as it does uncached' - results == [2, 2, 2, 2] - service.calls == 8 + results == [2, 2, 2, 2, 2, 2] + service.calls == 10 and: 'each missing cache is reported once' log.events*.formattedMessage == [ "CachedService does not cache with missing: its cache manager, ${ConcurrentMapCacheManager.name}, " + - 'has no cache of that name, so the methods run uncached. Configure the cache in that cache manager, ' + - 'or define the one to cache with as grailsCacheManager.', + 'has no cache of that name, so the methods run uncached. Configure the cache in that cache manager.', "CachedService does not cache with gone: its cache manager, ${ConcurrentMapCacheManager.name}, " + - 'has no cache of that name, so the methods run uncached. Configure the cache in that cache manager, ' + - 'or define the one to cache with as grailsCacheManager.', + 'has no cache of that name, so the methods run uncached. Configure the cache in that cache manager.', ] as List - when: 'a cache the cache manager does have' + when: 'caches the cache manager does have, with the default key and with a key closure' service.calls = 0 - List cached = [service.cachedWhereConfigured(1), service.cachedWhereConfigured(1)] + List cached = [service.cachedWhereConfigured(1), service.cachedWhereConfigured(1), + service.cachedByKeyWhereConfigured(1), service.cachedByKeyWhereConfigured(1)] - then: 'still caches' - cached == [3, 3] - service.calls == 1 + then: 'still cache' + cached == [3, 3, 4, 4] + service.calls == 2 cleanup: log?.close() + context?.close() where: mode << ['statically', 'dynamically'] @@ -91,9 +105,15 @@ class CachedService { @Cacheable('missing') int cached(int x) { calls++; x * 2 } + @Cacheable(value = 'missing', key = { x }) + int cachedByKey(int x) { calls++; x * 2 } + @Cacheable('configured') int cachedWhereConfigured(int x) { calls++; x * 3 } + @Cacheable(value = 'configured', key = { x + 100 }) + int cachedByKeyWhereConfigured(int x) { calls++; x * 4 } + @CachePut('missing') int put(int x) { calls++; x * 2 } diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy new file mode 100644 index 00000000000..f186dbc62aa --- /dev/null +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy @@ -0,0 +1,176 @@ +/* + * 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.function.Supplier + +import jakarta.annotation.Priority + +import org.springframework.beans.BeansException +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.config.BeanDefinitionCustomizer +import org.springframework.beans.factory.support.AbstractBeanDefinition +import org.springframework.cache.CacheManager +import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import org.springframework.context.annotation.AnnotationConfigUtils +import org.springframework.context.support.GenericApplicationContext +import spock.lang.Specification + +/** + * Which cache manager a cache-aware class is injected with, with the alias of {@code grailsCacheManager}, + * against the oracle of 8.0.0: the same class, in the same context, without it. + * + *

The matrix crosses the ways a bean named {@code grailsCacheManager} can be defined with none, one + * or two other cache managers, each defined in one of the ways a bean is chosen or passed over for + * injection. The deliberate differences: where Spring could not choose, which failed startup, the class + * gets {@code grailsCacheManager}, unless two cache managers are marked primary, which Spring rejects + * before it looks at names; and where it chose a cache manager by its {@code @Priority} beside + * {@code grailsCacheManager}, the name now comes first. Otherwise the choice, and every failure, is + * 8.0.0's, and no cache manager is created that 8.0.0 did not create, other than {@code grailsCacheManager}.

+ */ +class GrailsCacheManagerAliasMatrixSpec extends Specification { + + private static final String NAMED = GrailsCacheManagerAliasRegistrar.CACHE_MANAGER_BEAN_NAME + + private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType'] + + private static final List OTHER_KINDS = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', 'priority'] + + void 'the alias is the name the trait\'s field has in a class that implements it'() { + expect: + CacheAware.declaredFields*.name.contains(GrailsCacheManagerAliasRegistrar.ALIAS) + } + + void 'the cache manager a cache-aware class gets is 8.0.0\'s, except where it failed or chose by priority'() { + given: + List> rows = arrangements() + assert rows.size() == NAMED_KINDS.size() * (1 + OTHER_KINDS.size() + OTHER_KINDS.size() * OTHER_KINDS.size()) + + expect: 'every arrangement, each in a context of its own, with the alias and without it' + List mismatches = [] + rows.each { Map row -> + Map was = run(row, false) + Map now = run(row, true) + boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy'] + // Spring rejects two primary candidates before it looks at names, as it did in 8.0.0 + boolean twoPrimaries = row.values().count { it == 'primary' } > 1 + boolean choseByPriority = !was.failed && was.chosen != NAMED && row[was.chosen as String] == 'priority' + Object expected = (namedUsable && !twoPrimaries && (was.failed || choseByPriority)) ? NAMED : + (was.failed ? 'failed' : was.chosen) + Object got = now.failed ? 'failed' : now.chosen + List allowedToCreate = ((List) was.created) + [NAMED] + if (got != expected) { + mismatches << "${row}: got ${got}, expected ${expected} (8.0.0: ${was.failed ? 'failed' : was.chosen})".toString() + } + else if (!allowedToCreate.containsAll((List) now.created)) { + mismatches << "${row}: created ${now.created}, where 8.0.0 created ${was.created}".toString() + } + } + mismatches == [] + } + + void 'no alias is registered where there is no grailsCacheManager, or where its name is taken'() { + given: + GenericApplicationContext withNone = context([first: 'plain'], [:], [], true) + GenericApplicationContext taken = context([(NAMED): 'plain'], [:], [], false) + taken.beanFactory.registerAlias('first', GrailsCacheManagerAliasRegistrar.ALIAS) + taken.registerBean('first', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) + + when: + new GrailsCacheManagerAliasRegistrar().postProcessBeanFactory(taken.beanFactory) + + then: + !withNone.beanFactory.isAlias(GrailsCacheManagerAliasRegistrar.ALIAS) + taken.beanFactory.getAliases('first').contains(GrailsCacheManagerAliasRegistrar.ALIAS) + !taken.beanFactory.getAliases(NAMED).contains(GrailsCacheManagerAliasRegistrar.ALIAS) + + cleanup: + withNone?.close() + taken?.close() + } + + private Map run(Map row, boolean withAlias) { + Map instances = [:] + List created = [] + GenericApplicationContext context = context(row, instances, created, withAlias) + List atStartup = new ArrayList<>(created) + Map result = [failed: false] + try { + CacheManager chosen = ((CacheAware) context.getBean('probe')).grailsCacheManager + result.chosen = chosen == null ? null : instances.find { String name, CacheManager instance -> instance.is(chosen) }?.key + } + catch (BeansException ignored) { + result.failed = true + } + result.created = created - atStartup + context.close() + result + } + + private GenericApplicationContext context(Map row, Map instances, + List created, boolean withAlias) { + GenericApplicationContext context = new GenericApplicationContext() + AnnotationConfigUtils.registerAnnotationConfigProcessors(context) + if (withAlias) { + context.addBeanFactoryPostProcessor(new GrailsCacheManagerAliasRegistrar()) + } + row.each { String name, String kind -> + if (kind == 'wrongType') { + context.registerBean(name, String, { -> 'not a cache manager' } as Supplier) + return + } + Class type = kind == 'priority' ? HighPriorityCacheManager : ConcurrentMapCacheManager + Supplier supplier = { -> + created << name + CacheManager instance = type.getDeclaredConstructor().newInstance() + instances[name] = instance + instance + } as Supplier + BeanDefinitionCustomizer customizer = { BeanDefinition definition -> + AbstractBeanDefinition bean = (AbstractBeanDefinition) definition + bean.primary = kind == 'primary' + bean.lazyInit = kind == 'lazy' + bean.autowireCandidate = kind != 'notCandidate' + bean.fallback = kind == 'fallback' + bean.defaultCandidate = kind != 'notDefault' + } as BeanDefinitionCustomizer + context.registerBean(name, (Class) type, supplier, customizer) + } + BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer + context.registerBean('probe', CacheAware, lazy) + context.refresh() + context + } + + private static List> arrangements() { + List> others = [[:]] + OTHER_KINDS.each { String first -> others << [first: first] } + OTHER_KINDS.each { String first -> OTHER_KINDS.each { String second -> others << [first: first, second: second] } } + NAMED_KINDS.collectMany { String named -> + others.collect { Map other -> named == 'absent' ? other : ([(NAMED): named] + other) } + } + } + + static class CacheAware implements GrailsCacheManagerAware { + } + + @Priority(1) + static class HighPriorityCacheManager extends ConcurrentMapCacheManager { + } +} diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy deleted file mode 100644 index 83589030e8c..00000000000 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerLookupMatrixSpec.groovy +++ /dev/null @@ -1,457 +0,0 @@ -/* - * 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.function.Supplier - -import jakarta.annotation.Priority - -import ch.qos.logback.classic.Level -import org.codehaus.groovy.control.CompilationUnit -import org.codehaus.groovy.control.CompilerConfiguration -import org.codehaus.groovy.control.Phases -import org.codehaus.groovy.tools.GroovyClass -import org.springframework.beans.BeansException -import org.springframework.beans.factory.ObjectFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor -import org.springframework.beans.factory.config.BeanDefinition -import org.springframework.beans.factory.config.BeanDefinitionCustomizer -import org.springframework.beans.factory.config.Scope -import org.springframework.beans.factory.support.AbstractBeanDefinition -import org.springframework.beans.factory.support.DefaultListableBeanFactory -import org.springframework.beans.factory.support.RootBeanDefinition -import org.springframework.beans.factory.support.ScopeNotActiveException -import org.springframework.cache.CacheManager -import org.springframework.cache.concurrent.ConcurrentMapCacheManager -import org.springframework.context.annotation.AnnotationConfigUtils -import org.springframework.context.support.GenericApplicationContext -import spock.lang.Shared -import spock.lang.Specification - -import org.apache.grails.core.testing.support.LogCapture - -/** - * Which cache manager a cache-aware class gets, against the oracle of what Spring injected into the - * trait's {@code @Autowired(required = false) CacheManager} field before the trait chose it itself. - * The matrix crosses the ways a bean named {@code grailsCacheManager} can be defined with none, one - * or two other cache managers, each defined in one of the ways a bean is chosen or passed over for - * injection, all in one context; the features after it cover the arrangements it does not. - * - *

The deliberate differences: a cache manager named {@code grailsCacheManager} is used whenever - * there is one, as the plugin and its tag library use it by name; and where Spring cannot choose, which - * failed startup, there is none. Either way no cache manager is created that the injection would not - * have created, other than the one returned.

- */ -class GrailsCacheManagerLookupMatrixSpec extends Specification { - - private static final List NAMED = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType'] - - private static final List OTHER = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', 'priority'] - - @Shared - List> rows = arrangements() - - void 'the cache manager a cache-aware class gets matches what Spring injected, except where deliberate'() { - expect: 'every arrangement, each run against the oracle in a context of its own' - List mismatches = [] - rows.each { Map row -> - Map oracle = run(row, Injected) - Map lookup = run(row, CacheAware) - Object expected - if (row.containsKey(GrailsCacheManagerLookup.BEAN_NAME) && row[GrailsCacheManagerLookup.BEAN_NAME] != 'wrongType') { - expected = GrailsCacheManagerLookup.BEAN_NAME - } - else { - expected = oracle.failed ? null : oracle.chosen - } - List allowedToCreate = ((List) oracle.created) + (expected ? [expected as String] : []) - if (lookup.failed) { - mismatches << "${row}: the lookup failed: ${lookup.failure}".toString() - } - else if (lookup.chosen != expected) { - mismatches << "${row}: got ${lookup.chosen}, expected ${expected} (Spring injected ${oracle.failed ? 'nothing, it failed' : oracle.chosen})".toString() - } - else if (!allowedToCreate.containsAll((List) lookup.created)) { - mismatches << "${row}: created ${lookup.created}, where the injection created ${oracle.created}".toString() - } - } - mismatches == [] - } - - void 'the matrix covers the arrangements it says it does'() { - expect: 'six arrangements of the named one, and none, one or two of the seven others' - rows.size() == NAMED.size() * (1 + OTHER.size() + OTHER.size() * OTHER.size()) - } - - void 'where Spring cannot choose, the class does not cache, and a warning says why'() { - given: 'two cache managers, neither primary nor named grailsCacheManager, which failed startup when injected' - GenericApplicationContext context = context([first: 'plain', second: 'plain'], [:]) - LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.WARN) - - when: - CacheManager found = context.getBean('probe', CacheAware).grailsCacheManager - - then: 'it names the class and the cache managers, in Spring\'s words' - found == null - log.events.size() == 1 - log.events[0].formattedMessage.startsWith("${CacheAware.name} does not cache: there is no cache manager named grailsCacheManager") - log.events[0].formattedMessage.contains('first,second') - - cleanup: - log?.close() - context?.close() - } - - void 'two cache managers marked primary are reported in Spring\'s words, rather than as a list it does not give'() { - given: - GenericApplicationContext context = context([first: 'primary', second: 'primary'], [:]) - LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.WARN) - - when: - CacheManager found = context.getBean('probe', CacheAware).grailsCacheManager - - then: - found == null - log.events.size() == 1 - log.events[0].formattedMessage.contains("more than one 'primary' bean found") - !log.events[0].formattedMessage.contains('null') - - cleanup: - log?.close() - context?.close() - } - - void 'a primary cache manager passed over for grailsCacheManager is reported once'() { - given: 'an application cache manager marked primary, and two cache-aware beans' - GenericApplicationContext context = context([grailsCacheManager: 'plain', redis: 'primary'], [:]) - context.registerBean('another', CacheAware, { -> new CacheAware() } as Supplier) - LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) - - when: - context.getBean('probe', CacheAware).grailsCacheManager - context.getBean('another', CacheAware).grailsCacheManager - - then: - log.events*.formattedMessage == ['Grails caches with the cache manager named grailsCacheManager, not with redis, ' + - 'which Spring prefers as primary or by priority. Define the one to cache with as grailsCacheManager.'] - - cleanup: - log?.close() - context?.close() - } - - void 'a cache manager passed over that Spring prefers by priority, or that is primary in a parent context, is reported'() { - given: - GenericApplicationContext parent = context([redis: 'primary'], [:]) - GenericApplicationContext child = context([grailsCacheManager: 'plain', hazelcast: 'priority'], [:], [], CacheAware, parent) - LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) - - when: - child.getBean('probe', CacheAware).grailsCacheManager - - then: - log.events.size() == 1 - log.events[0].formattedMessage.contains('not with hazelcast, redis,') - - cleanup: - log?.close() - child?.close() - parent?.close() - } - - void 'a cache manager registered as a singleton beside grailsCacheManager is reported by its priority, and fails nothing'() { - given: 'cache managers with no bean definition, one of a class with a priority' - GenericApplicationContext context = context([grailsCacheManager: 'plain'], [:]) - context.beanFactory.registerSingleton('plainSingleton', new ConcurrentMapCacheManager()) - context.beanFactory.registerSingleton('prioritySingleton', new HighPriorityCacheManager()) - LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) - - when: - CacheManager found = context.getBean('probe', CacheAware).grailsCacheManager - - then: - found.is(context.getBean('grailsCacheManager')) - log.events*.formattedMessage == ['Grails caches with the cache manager named grailsCacheManager, not with ' + - 'prioritySingleton, which Spring prefers as primary or by priority. Define the one to cache with as grailsCacheManager.'] - - cleanup: - log?.close() - context?.close() - } - - void 'a cache manager is not chosen for being named like a parameter of the injection method'() { - given: 'a cache-aware class compiled keeping parameter names, as the Grails Gradle plugin compiles an application' - Class compiled = compiledWithParameterNames(''' - package names - class NamedCacheAware implements org.grails.plugin.cache.GrailsCacheManagerAware { - } - ''', 'names.NamedCacheAware') - - and: 'cache managers named as such a parameter might be, none primary, which Spring matches by name only then' - GenericApplicationContext context = context( - [cacheManagers: 'plain', cacheManager: 'plain', candidates: 'plain', beanFactory: 'plain'], [:], [], compiled) - - expect: 'none is chosen for its name, as none was for the field the trait had, whose name matched no bean' - context.getBean('probe').grailsCacheManager == null - - cleanup: - context?.close() - } - - void 'a primary cache manager that Spring would not inject is not reported as passed over'() { - given: 'one excluded from injection, and one that is not a default candidate' - GenericApplicationContext context = context( - [grailsCacheManager: 'plain', first: 'primary+notCandidate', second: 'primary+notDefault'], [:]) - LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) - - when: - context.getBean('probe', CacheAware).grailsCacheManager - - then: - log.events == [] - - cleanup: - log?.close() - context?.close() - } - - void 'in a bean factory that is not an application context, the cache manager is still the one Spring injects'() { - given: 'a bare bean factory, which does not inject itself, processing @Autowired' - DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory() - beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor(beanFactory: beanFactory)) - CacheManager only = new ConcurrentMapCacheManager() - beanFactory.registerSingleton('cacheManager', only) - beanFactory.registerBeanDefinition('probe', new RootBeanDefinition(CacheAware)) - - expect: - beanFactory.getBean('probe', CacheAware).grailsCacheManager.is(only) - } - - void 'a cache manager whose scope is not active fails the bean, as its injection did'() { - given: 'the only cache manager, in a scope with no active instance, with no proxy' - GenericApplicationContext context = new GenericApplicationContext() - AnnotationConfigUtils.registerAnnotationConfigProcessors(context) - context.beanFactory.registerScope('inactive', new Scope() { - Object get(String name, ObjectFactory factory) { - throw new ScopeNotActiveException(name, 'inactive', new IllegalStateException('no active instance')) - } - Object remove(String name) { null } - void registerDestructionCallback(String name, Runnable callback) { } - Object resolveContextualObject(String key) { null } - String getConversationId() { null } - }) - BeanDefinitionCustomizer inactive = { BeanDefinition definition -> definition.scope = 'inactive' } as BeanDefinitionCustomizer - context.registerBean('cacheManager', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier, inactive) - BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer - context.registerBean('injected', Injected, lazy) - context.registerBean('probe', CacheAware, lazy) - context.refresh() - - when: - context.getBean('injected') - - then: 'the oracle' - thrown(BeansException) - - when: - context.getBean('probe') - - then: - BeansException e = thrown() - e.mostSpecificCause instanceof IllegalStateException - - cleanup: - context?.close() - } - - void 'no primary cache manager is reported where grailsCacheManager is an alias of the primary one'() { - given: 'the primary cache manager, under another name, aliased as grailsCacheManager' - GenericApplicationContext context = context([redis: 'primary'], [:]) - context.registerAlias('redis', 'grailsCacheManager') - LogCapture log = new LogCapture(GrailsCacheManagerLookup, Level.INFO) - - when: - context.getBean('probe', CacheAware).grailsCacheManager - - then: - log.events == [] - - cleanup: - log?.close() - context?.close() - } - - void 'the cache manager is chosen when the bean is created, as an injected one was'() { - given: 'a bean created in a context with no cache manager' - GenericApplicationContext context = context([:], [:]) - CacheAware aware = context.getBean('probe', CacheAware) - - when: 'one is defined before the bean is first asked for its cache manager' - context.registerBean('later', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) - - then: 'it would be found, but the choice was made when the bean was created' - context.getBean('later') instanceof CacheManager - aware.grailsCacheManager == null - - cleanup: - context.close() - } - - void 'a class compiled against the trait 8.0.0 shipped works with this one'() { - given: 'a cached class compiled together with that trait, of which only the class is loaded beside this one' - Class compiled = compiledAgainst800(''' - package compat - class OldCacheAware implements org.grails.plugin.cache.GrailsCacheManagerAware { - } - ''', 'compat.OldCacheAware') - - expect: 'created on its own, it has no cache manager, rather than throwing' - compiled.getDeclaredConstructor().newInstance().grailsCacheManager == null - - when: 'created as a bean, it is injected through the field it declares, as with 8.0.0' - CacheManager only = new ConcurrentMapCacheManager() - GenericApplicationContext context = new GenericApplicationContext() - AnnotationConfigUtils.registerAnnotationConfigProcessors(context) - context.registerBean('cacheManager', CacheManager, { -> only } as Supplier) - context.registerBean('old', (Class) compiled) - context.refresh() - - then: - context.getBean('old').grailsCacheManager.is(only) - - cleanup: - context?.close() - } - - /** Compiles the source against this trait, keeping parameter names, and loads it. */ - private Class compiledWithParameterNames(String source, String className) { - CompilerConfiguration configuration = new CompilerConfiguration() - configuration.parameters = true - new GroovyClassLoader(getClass().classLoader, configuration).with { - parseClass(source) - loadClass(className) - } - } - - /** - * Compiles the source with the trait as 8.0.0 shipped it, and loads only the class, so that the - * trait it runs against is this one, as for a plugin compiled against 8.0.0. - */ - private Class compiledAgainst800(String source, String className) { - String trait800 = getClass().getResource('GrailsCacheManagerAware-8.0.0.groovy.txt').text - CompilationUnit unit = new CompilationUnit(new CompilerConfiguration(), null, new GroovyClassLoader(getClass().classLoader)) - unit.addSource('GrailsCacheManagerAware.groovy', trait800) - unit.addSource('OldCacheAware.groovy', source) - // up to class generation only, so that nothing is written to the working directory - unit.compile(Phases.CLASS_GENERATION) - Map classes = unit.classes.collectEntries { GroovyClass compiled -> [(compiled.name): compiled.bytes] } - assert classes.keySet().any { it.startsWith('org.grails.plugin.cache.GrailsCacheManagerAware') } - ClassLoader loader = new ClassLoader(getClass().classLoader) { - @Override - protected Class findClass(String name) { - byte[] bytes = name.startsWith('org.grails.plugin.cache.') ? null : classes[name] - if (bytes == null) { - throw new ClassNotFoundException(name) - } - defineClass(name, bytes, 0, bytes.length) - } - } - loader.loadClass(className) - } - - private Map run(Map row, Class probe) { - Map instances = [:] - List created = [] - GenericApplicationContext context = context(row, instances, created, probe) - List atStartup = new ArrayList<>(created) - Map result = [failed: false] - try { - Object bean = context.getBean('probe') - CacheManager chosen = probe == Injected ? ((Injected) bean).injected : ((CacheAware) bean).grailsCacheManager - result.chosen = chosen == null ? null : instances.find { String name, CacheManager instance -> instance.is(chosen) }?.key - } - catch (BeansException e) { - result.failed = true - result.failure = e.message - } - result.created = created - atStartup - context.close() - result - } - - private GenericApplicationContext context(Map row, Map instances, - List created = [], Class probe = CacheAware, - GenericApplicationContext parent = null) { - GenericApplicationContext context = new GenericApplicationContext(parent) - AnnotationConfigUtils.registerAnnotationConfigProcessors(context) - row.each { String name, String kind -> - if (kind == 'wrongType') { - context.registerBean(name, String, { -> 'not a cache manager' } as Supplier) - return - } - Set attributes = kind.split(/\+/) as Set - Class type = 'priority' in attributes ? HighPriorityCacheManager : ConcurrentMapCacheManager - Supplier supplier = { -> - created << name - CacheManager instance = type.getDeclaredConstructor().newInstance() - instances[name] = instance - instance - } as Supplier - BeanDefinitionCustomizer customizer = { BeanDefinition definition -> - AbstractBeanDefinition bean = (AbstractBeanDefinition) definition - bean.primary = 'primary' in attributes - bean.lazyInit = 'lazy' in attributes - bean.autowireCandidate = !('notCandidate' in attributes) - bean.fallback = 'fallback' in attributes - bean.defaultCandidate = !('notDefault' in attributes) - } as BeanDefinitionCustomizer - context.registerBean(name, (Class) type, supplier, customizer) - } - BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer - context.registerBean('probe', (Class) probe, lazy) - context.refresh() - context - } - - private static List> arrangements() { - List> others = [[:]] - OTHER.each { String first -> others << [first: first] } - OTHER.each { String first -> OTHER.each { String second -> others << [first: first, second: second] } } - NAMED.collectMany { String named -> - others.collect { Map other -> - named == 'absent' ? other : ([(GrailsCacheManagerLookup.BEAN_NAME): named] + other) - } - } - } - - /** What Spring injected into the trait's field, under a name that, like the trait's renamed field, matches no bean. */ - static class Injected { - - @Autowired(required = false) - CacheManager injected - } - - static class CacheAware implements GrailsCacheManagerAware { - } - - @Priority(1) - static class HighPriorityCacheManager extends ConcurrentMapCacheManager { - } -} diff --git a/grails-cache/src/test/resources/org/grails/plugin/cache/GrailsCacheManagerAware-8.0.0.groovy.txt b/grails-cache/src/test/resources/org/grails/plugin/cache/GrailsCacheManagerAware-8.0.0.groovy.txt deleted file mode 100644 index 932c5f093f4..00000000000 --- a/grails-cache/src/test/resources/org/grails/plugin/cache/GrailsCacheManagerAware-8.0.0.groovy.txt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 groovy.transform.CompileStatic - -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.cache.CacheManager - -import grails.plugin.cache.CustomCacheKeyGenerator -import grails.plugin.cache.GrailsCacheKeyGenerator - -/** - * A trait for classes that are cache aware - * - * @since 4.0 - * @author Graeme Rocher - */ -@CompileStatic -trait GrailsCacheManagerAware { - - @Autowired(required = false) - private GrailsCacheKeyGenerator customCacheKeyGenerator = new CustomCacheKeyGenerator() - - @Autowired(required = false) - private CacheManager grailsCacheManager - - /** - * @return The Grails cache manager or null if it isn't present - */ - CacheManager getGrailsCacheManager() { - return grailsCacheManager - } - - /** - * @return The custom key generator, or null if it isn't present - */ - GrailsCacheKeyGenerator getCustomCacheKeyGenerator() { - return customCacheKeyGenerator - } -} diff --git a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc index 79751b119f1..cd7a4522c5e 100644 --- a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc +++ b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc @@ -21,8 +21,8 @@ The plugin registers an instance of the link:{springapi}/org/springframework/cac The most common method you would call on the `grailsCacheManager` is `getCache(String name)` to access a link:{springapi}/org/springframework/cache/Cache.html[Cache] instance programmatically. This shouldn't be needed often however. From the `Cache` instance you can also access the underlying cache implementation using `cache.getNativeCache()`. -The cache annotations and the cache tags cache with the `grailsCacheManager` bean. A cache provider plugin replaces it by defining a bean of that name, and an application can do the same with a `GrailsCacheManager` of its own. Another cache manager in the application context does not change which one is used, even when Spring would prefer it, as primary or by priority. That might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. Grails logs once, at INFO level, that it passed a preferred one over. +The cache annotations and the cache tags cache with the `grailsCacheManager` bean. A cache provider plugin replaces it by defining a bean of that name, and an application can do the same with a `GrailsCacheManager` of its own. -With caching turned off (`grails.cache.enabled: false`), the plugin defines no `grailsCacheManager`. Unless the application defines one, the annotations cache with the cache manager Spring would inject, such as the only one in the context or the one marked primary. Where Spring cannot choose one, they do not cache, and a warning gives Spring's reason. +The annotations receive their cache manager by type. Where the application context has another cache manager too, Spring uses the one marked primary, and where none is, `grailsCacheManager`, also over one with a `@Priority`. That other cache manager might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. A cache manager may have no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with. The annotated method then runs uncached, and a warning names the class and the cache once for each cache manager. diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index b7e690b2f4e..c26d838c19c 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -4973,18 +4973,10 @@ As of Grails 8.0.1, an exception an action throws is recorded as an error on the See the `rlike` entry of the criteria reference for the databases that match with a regular expression. -==== 94. Cache Annotations Use `grailsCacheManager` When Another Cache Manager Is Defined +==== 94. A Second Cache Manager No Longer Stops a Cached Application From Starting -Grails 8.0.0 injected the cache manager the cache annotations use by type. An application context with a second `CacheManager` beside the plugin's `grailsCacheManager` therefore failed to start unless one of them was marked primary, and that is what happens when the Spring Security plugin's `cacheUsers` is set. Grails now chooses the cache manager this way: +The cache annotations receive their cache manager by type. Grails 8.0.0 failed to start when the application context had a second `CacheManager` beside the plugin's `grailsCacheManager` and neither was marked primary, which is what happens when the Spring Security plugin's `cacheUsers` is set. Spring now uses `grailsCacheManager` there. Where one of them is marked primary, Spring uses that one, as before, and with caching turned off (`grails.cache.enabled: false`) nothing changes. This applies to classes compiled against Grails 8.0.0 too, so plugins need not be recompiled. -* The bean named `grailsCacheManager` comes first. -* Where there is none, as when `grails.cache.enabled` is `false`, it is the cache manager Spring would inject: the only one, or the one marked primary. -* Where Spring cannot choose one, the class does not cache, and a warning gives Spring's reason. Grails 8.0.0 failed to start in that case. +One case changes: a cache manager with a `@Priority`, not marked primary, beside `grailsCacheManager`. The annotations used it in 8.0.0, and now use `grailsCacheManager`. Mark it primary to keep caching with it. -Where the cache manager has no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with, the method now runs uncached, and a warning names the class and the cache once. Grails 8.0.0 failed with a `NullPointerException` on each call. This applies to classes compiled against this version. - -In an application that marked a cache manager of its own primary, or gave it a priority, next to `grailsCacheManager`, the cache annotations used that cache manager. They now use `grailsCacheManager`, and Grails logs once, at INFO level, that it passed the preferred one over. To keep caching with another cache manager, define it as the `grailsCacheManager` bean. It has to implement `GrailsCacheManager`, as the cache tags and the plugin's startup use it too. - -A cached class in a plugin compiled against Grails 8.0.0 keeps injecting its cache manager by type until the plugin is compiled against a later version. Until then, next to a second cache manager, such as the one `cacheUsers` defines, that class still fails to be created as it did with 8.0.0, unless one of the two is marked primary or has a priority. - -The other way round, a plugin with cached classes compiled against this version needs the cache plugin of this version at runtime too: with that of 8.0.0, Spring fails to create those classes as beans, as they call a method of the cache plugin that 8.0.0 does not have. Such a plugin declares `grailsVersion = '8.0.1 > *'`, so that Grails warns at startup when it runs on an earlier version. +Where the cache manager has no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with, the annotated method now runs uncached, and a warning names the class and the cache once. Grails 8.0.0 failed with a `NullPointerException` on each call. This applies to classes compiled against this version. diff --git a/grails-skills/upgrade-guide-8/skills/grails-8-upgrade/SKILL.md b/grails-skills/upgrade-guide-8/skills/grails-8-upgrade/SKILL.md index 8e5eb378932..d15c34d7ccc 100644 --- a/grails-skills/upgrade-guide-8/skills/grails-8-upgrade/SKILL.md +++ b/grails-skills/upgrade-guide-8/skills/grails-8-upgrade/SKILL.md @@ -575,6 +575,12 @@ Check plugin compatibility before treating a Grails 8 runtime failure as an appl - A plugin referencing the removed `grails.gorm.annotation.AutoTimestamp` can fail even if the application does not use that annotation. Upgrade the plugin or fix its optional annotation lookup; adding application mocks does not fix the class-linkage error. Plugins doing configuration work in `doWithSpring` must use the supplied `grailsApplication` and avoid prematurely instantiating Spring Security services during bean registration. - Check the Grails issue tracker and each plugin release notes before upgrading plugin-dependent applications. +### Cache Plugin Beside Another Cache Manager + +- From Grails 8.0.1, a second `CacheManager` beside the cache plugin's `grailsCacheManager`, such as the one the Spring Security plugin defines with `cacheUsers`, no longer stops a cached application from starting: where neither is marked primary, Spring uses `grailsCacheManager`, also for classes compiled against 8.0.0. A primary cache manager is still used, and nothing changes with `grails.cache.enabled: false`. +- A cache manager with a `@Priority`, not marked primary, beside `grailsCacheManager` was used by the cache annotations in 8.0.0 and no longer is. Mark it primary to keep caching with it. +- A cache manager without a cache of an annotation's name, such as a `JCacheCacheManager` the cache was not configured in, made every call fail with a `NullPointerException`. Classes compiled against 8.0.1 run uncached there, with one warning naming the class and the cache. + ### Custom CSRF / Synchronizer-Token Holders - Audit subclasses of `SynchronizerTokensHolder`: `withForm` now validates and consumes tokens through `isValidAndResetToken(url, token)`. Overriding only `resetToken` no longer preserves an application's reusable AJAX/session token. The characteristic failure is that the first AJAX POST succeeds, then later requests fail CSRF validation because the token URL has disappeared from the holder. From 3b3a79c82143bd8b2989504fec6858e8cd15d87e Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Wed, 18 Nov 2026 14:13:33 -0800 Subject: [PATCH 13/20] Check an application's own grailsCacheManager beside another one The alias registrar's javadoc says a grailsCacheManager the application or a cache provider plugin defines gets the alias too, but only the matrix, which adds the registrar by hand, checked it. A feature of CacheAutoConfigurationSpec now defines one beside a second cache manager and checks, through the plugin's auto-configuration, that a cache-aware bean and GrailsCacheAdminService get it. Without the registrar it fails with the startup error the fix is for. --- .../plugin/cache/CacheAutoConfigurationSpec.groovy | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 50b7d9946a4..34f32c24774 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -150,6 +150,19 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } + void 'a grailsCacheManager the application defines is used beside another cache manager'() { + given: 'a cache manager of the application\'s own as grailsCacheManager, and Spring Security\'s beside it' + GrailsCacheManager mine = Mock(GrailsCacheManager) + AnnotationConfigApplicationContext context = buildContext([:], mine, [cacheManager: new ConcurrentMapCacheManager()]) + + expect: 'it gets the alias too, so the context starts and caches with it' + context.getBean(CacheAware).grailsCacheManager.is(mine) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(mine) + + cleanup: + context.close() + } + void 'another cache manager in the context, such as the one Spring Security caches users with, is not taken for the Grails one'() { given: 'Spring Security defines cacheManager when cacheUsers is set' CacheManager other = new ConcurrentMapCacheManager() From 4d4da50f11fd2ad6dc260f58765650765dcf296f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Wed, 18 Nov 2026 23:26:35 -0800 Subject: [PATCH 14/20] Leave the alias out beside a primary cache manager or one with a priority Spring takes a bean named like the field before one with a higher priority, so with the alias grailsCacheManager beat a @Priority cache manager Spring had injected in 8.0.0. Where the application's grailsCacheManager is created from a cache-aware bean, that bean then asked for grailsCacheManager while it was being created, and startup failed; 8.0.0 started and injected the @Priority one. The registrar now registers the alias only where no other cache manager is marked primary or has a priority, read from the bean definitions, or for a singleton without one from its class, so Spring keeps its 8.0.0 choice there, and grailsCacheManager is taken only where 8.0.0 could not choose. That also drops the one choice 8.0.1 changed, and its upgrade note. The matrix gains a grailsCacheManager created from the cache-aware bean, and expects 8.0.0's result except where 8.0.0 failed with no preferred cache manager; with the previous registrar, 11 such rows beside a @Priority cache manager fail to start. CacheAutoConfigurationSpec covers the case through the auto-configuration, with a @Priority and a primary cache manager. --- .../GrailsCacheManagerAliasRegistrar.groovy | 65 ++++++++++++++++++- .../cache/CacheAutoConfigurationSpec.groovy | 41 ++++++++++++ .../GrailsCacheManagerAliasMatrixSpec.groovy | 56 +++++++++++----- .../guide/cache/cacheUsage/cacheManager.adoc | 2 +- .../src/en/guide/upgrading/upgrading80x.adoc | 4 +- .../upgrade/skills/grails-upgrade/SKILL.md | 3 +- 6 files changed, 145 insertions(+), 26 deletions(-) diff --git a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy index c8cb64b0412..c29a29fc9c0 100644 --- a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy @@ -19,10 +19,17 @@ package org.grails.plugin.cache import groovy.transform.CompileStatic +import groovy.util.logging.Slf4j import org.springframework.beans.BeansException +import org.springframework.beans.factory.BeanFactoryUtils +import org.springframework.beans.factory.NoSuchBeanDefinitionException +import org.springframework.beans.factory.config.BeanDefinition import org.springframework.beans.factory.config.BeanFactoryPostProcessor import org.springframework.beans.factory.config.ConfigurableListableBeanFactory +import org.springframework.beans.factory.support.AbstractBeanDefinition +import org.springframework.cache.CacheManager +import org.springframework.core.annotation.OrderUtils /** * Names the cache manager called {@code grailsCacheManager} after the field a cache-aware class has it @@ -33,7 +40,15 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory * 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. With this * alias the renamed field matches {@code grailsCacheManager}. Where Spring could choose, which is the - * only cache manager or the one marked primary, nothing changes.

+ * only cache manager, or one marked primary or with a priority, nothing changes.

+ * + *

Spring takes a bean named like the field before one with a higher priority, so the alias is left + * out where another cache manager is marked primary or has a priority, to keep Spring's choice there. + * Otherwise a {@code grailsCacheManager} created from a cache-aware bean, which Spring gave the other + * cache manager, would be asked for while it is being created, and fail. The priority is read from the + * class of the bean as its definition declares it, as no bean is created here; a priority that only + * the created object has, behind a factory method declared to return a {@code CacheManager}, is not + * seen.

* *

The alias is registered after every bean definition is in, so a {@code grailsCacheManager} that a * cache provider plugin or the application defines gets it too, and it is registered only where there @@ -41,6 +56,7 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory * * @since 8.0.1 */ +@Slf4j @CompileStatic class GrailsCacheManagerAliasRegistrar implements BeanFactoryPostProcessor { @@ -51,8 +67,53 @@ class GrailsCacheManagerAliasRegistrar implements BeanFactoryPostProcessor { @Override void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - if (beanFactory.containsBean(CACHE_MANAGER_BEAN_NAME) && !beanFactory.containsBean(ALIAS)) { + if (beanFactory.containsBean(CACHE_MANAGER_BEAN_NAME) && !beanFactory.containsBean(ALIAS) && + !anotherPreferred(beanFactory)) { beanFactory.registerAlias(CACHE_MANAGER_BEAN_NAME, ALIAS) } } + + /** Whether Spring prefers another cache manager over {@code grailsCacheManager}, as primary or by priority. */ + private static boolean anotherPreferred(ConfigurableListableBeanFactory beanFactory) { + BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, CacheManager, true, false).any { String name -> + name != CACHE_MANAGER_BEAN_NAME && !(CACHE_MANAGER_BEAN_NAME in beanFactory.getAliases(name)) && + preferredBySpring(beanFactory, name) + } + } + + /** + * Whether Spring prefers the cache manager when it injects one by type. One registered as a singleton + * has no bean definition, and only the priority of its class. One that is not a candidate for + * injection by type is never preferred. + */ + private static boolean preferredBySpring(ConfigurableListableBeanFactory beanFactory, String name) { + try { + BeanDefinition definition = definitionOf(beanFactory, name) + if (definition != null) { + if (!definition.autowireCandidate || + (definition instanceof AbstractBeanDefinition && !((AbstractBeanDefinition) definition).defaultCandidate)) { + return false + } + if (definition.primary) { + return true + } + } + Class type = beanFactory.getType(name, false) + return type != null && OrderUtils.getPriority(type) != null + } + catch (BeansException e) { + // a definition that cannot be read fails when its bean is created, not here + log.debug('Could not tell whether Spring prefers the cache manager {}', name, e) + return false + } + } + + private static BeanDefinition definitionOf(ConfigurableListableBeanFactory beanFactory, String name) { + try { + return beanFactory.getMergedBeanDefinition(name) + } + catch (NoSuchBeanDefinitionException ignored) { + return null + } + } } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 34f32c24774..2f6f91f61b6 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -22,7 +22,10 @@ import java.util.function.Supplier import groovy.transform.CompileStatic +import jakarta.annotation.Priority + import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.config.BeanDefinitionCustomizer import org.springframework.cache.CacheManager import org.springframework.cache.concurrent.ConcurrentMapCacheManager import org.springframework.context.annotation.AnnotationConfigApplicationContext @@ -163,6 +166,39 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } + @Unroll + void 'a grailsCacheManager built from a cache-aware bean starts beside a cache manager #preferred, which that bean gets, as in 8.0.0'() { + given: 'the application\'s grailsCacheManager, created from a bean that has a cache manager injected itself' + GrailsCacheManager mine = Mock(GrailsCacheManager) + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() + context.registerBean('grailsCacheManager', GrailsCacheManager, { -> + context.getBean(CacheAware) + mine + } as Supplier) + if (preferred == 'with a priority') { + context.registerBean('preferredCacheManager', HighPriorityCacheManager) + } + else { + context.registerBean('preferredCacheManager', ConcurrentMapCacheManager, + { BeanDefinition definition -> definition.primary = true } as BeanDefinitionCustomizer) + } + context.registerBean(CacheAware) + context.register(CacheAutoConfiguration) + + when: + context.refresh() + + then: 'the context starts, and the cache-aware beans get the cache manager Spring prefers' + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('preferredCacheManager')) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(context.getBean('preferredCacheManager')) + + cleanup: + context.close() + + where: + preferred << ['with a priority', 'marked primary'] + } + void 'another cache manager in the context, such as the one Spring Security caches users with, is not taken for the Grails one'() { given: 'Spring Security defines cacheManager when cacheUsers is set' CacheManager other = new ConcurrentMapCacheManager() @@ -243,6 +279,11 @@ class CacheAutoConfigurationSpec extends Specification { throw new IllegalStateException('the cache store is down') } as Supplier + /** A cache manager Spring prefers over others by the priority of its class. */ + @Priority(1) + static class HighPriorityCacheManager extends ConcurrentMapCacheManager { + } + /** A class the cache transformations make cache-aware, as they do a service with a cached method. */ static class CacheAware implements GrailsCacheManagerAware { } diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy index f186dbc62aa..4e4a7caaa53 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy @@ -38,17 +38,18 @@ import spock.lang.Specification * *

The matrix crosses the ways a bean named {@code grailsCacheManager} can be defined with none, one * or two other cache managers, each defined in one of the ways a bean is chosen or passed over for - * injection. The deliberate differences: where Spring could not choose, which failed startup, the class - * gets {@code grailsCacheManager}, unless two cache managers are marked primary, which Spring rejects - * before it looks at names; and where it chose a cache manager by its {@code @Priority} beside - * {@code grailsCacheManager}, the name now comes first. Otherwise the choice, and every failure, is - * 8.0.0's, and no cache manager is created that 8.0.0 did not create, other than {@code grailsCacheManager}.

+ * injection. One way to define {@code grailsCacheManager} creates it from the cache-aware bean, which so + * has a cache manager injected while {@code grailsCacheManager} is being created. The one deliberate + * difference: where Spring could not choose, which failed startup, the class gets + * {@code grailsCacheManager}, unless another cache manager is marked primary or has a priority, where + * Spring's choice is left as it was. Otherwise the choice, and every failure, is 8.0.0's, and no cache + * manager is created that 8.0.0 did not create, other than {@code grailsCacheManager}.

*/ class GrailsCacheManagerAliasMatrixSpec extends Specification { private static final String NAMED = GrailsCacheManagerAliasRegistrar.CACHE_MANAGER_BEAN_NAME - private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType'] + private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType', 'cyclic'] private static final List OTHER_KINDS = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', 'priority'] @@ -57,7 +58,7 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { CacheAware.declaredFields*.name.contains(GrailsCacheManagerAliasRegistrar.ALIAS) } - void 'the cache manager a cache-aware class gets is 8.0.0\'s, except where it failed or chose by priority'() { + void 'the cache manager a cache-aware class gets is 8.0.0\'s, except where it failed with none preferred'() { given: List> rows = arrangements() assert rows.size() == NAMED_KINDS.size() * (1 + OTHER_KINDS.size() + OTHER_KINDS.size() * OTHER_KINDS.size()) @@ -68,11 +69,8 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { Map was = run(row, false) Map now = run(row, true) boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy'] - // Spring rejects two primary candidates before it looks at names, as it did in 8.0.0 - boolean twoPrimaries = row.values().count { it == 'primary' } > 1 - boolean choseByPriority = !was.failed && was.chosen != NAMED && row[was.chosen as String] == 'priority' - Object expected = (namedUsable && !twoPrimaries && (was.failed || choseByPriority)) ? NAMED : - (was.failed ? 'failed' : was.chosen) + boolean anotherPreferred = row.any { String name, String kind -> name != NAMED && kind in ['primary', 'priority'] } + Object expected = (was.failed && namedUsable && !anotherPreferred) ? NAMED : (was.failed ? 'failed' : was.chosen) Object got = now.failed ? 'failed' : now.chosen List allowedToCreate = ((List) was.created) + [NAMED] if (got != expected) { @@ -85,41 +83,60 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { mismatches == [] } - void 'no alias is registered where there is no grailsCacheManager, or where its name is taken'() { + void 'no alias is registered where there is no grailsCacheManager, where its name is taken, or beside a preferred singleton'() { given: GenericApplicationContext withNone = context([first: 'plain'], [:], [], true) GenericApplicationContext taken = context([(NAMED): 'plain'], [:], [], false) taken.beanFactory.registerAlias('first', GrailsCacheManagerAliasRegistrar.ALIAS) taken.registerBean('first', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) + and: 'cache managers registered as singletons, which have no bean definition, one of a class with a priority' + GenericApplicationContext besidePriority = context([(NAMED): 'plain'], [:], [], false) + besidePriority.beanFactory.registerSingleton('preferred', new HighPriorityCacheManager()) + GenericApplicationContext besidePlain = context([(NAMED): 'plain'], [:], [], false) + besidePlain.beanFactory.registerSingleton('other', new ConcurrentMapCacheManager()) + when: - new GrailsCacheManagerAliasRegistrar().postProcessBeanFactory(taken.beanFactory) + [taken, besidePriority, besidePlain].each { GenericApplicationContext context -> + new GrailsCacheManagerAliasRegistrar().postProcessBeanFactory(context.beanFactory) + } then: !withNone.beanFactory.isAlias(GrailsCacheManagerAliasRegistrar.ALIAS) taken.beanFactory.getAliases('first').contains(GrailsCacheManagerAliasRegistrar.ALIAS) !taken.beanFactory.getAliases(NAMED).contains(GrailsCacheManagerAliasRegistrar.ALIAS) + !besidePriority.beanFactory.isAlias(GrailsCacheManagerAliasRegistrar.ALIAS) + + and: 'a singleton without a priority leaves the alias to be registered' + besidePlain.beanFactory.getAliases(NAMED).contains(GrailsCacheManagerAliasRegistrar.ALIAS) cleanup: withNone?.close() taken?.close() + besidePriority?.close() + besidePlain?.close() } private Map run(Map row, boolean withAlias) { Map instances = [:] List created = [] - GenericApplicationContext context = context(row, instances, created, withAlias) - List atStartup = new ArrayList<>(created) + List atStartup = [] Map result = [failed: false] + GenericApplicationContext started = null try { - CacheManager chosen = ((CacheAware) context.getBean('probe')).grailsCacheManager + // a cyclic grailsCacheManager has the probe injected while the context starts + started = context(row, instances, created, withAlias) + atStartup.addAll(created) + CacheManager chosen = ((CacheAware) started.getBean('probe')).grailsCacheManager result.chosen = chosen == null ? null : instances.find { String name, CacheManager instance -> instance.is(chosen) }?.key } catch (BeansException ignored) { result.failed = true } + finally { + started?.close() + } result.created = created - atStartup - context.close() result } @@ -137,6 +154,9 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { } Class type = kind == 'priority' ? HighPriorityCacheManager : ConcurrentMapCacheManager Supplier supplier = { -> + if (kind == 'cyclic') { + context.getBean('probe') + } created << name CacheManager instance = type.getDeclaredConstructor().newInstance() instances[name] = instance diff --git a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc index cd7a4522c5e..12f068d1bec 100644 --- a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc +++ b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc @@ -23,6 +23,6 @@ The most common method you would call on the `grailsCacheManager` is `getCache(S The cache annotations and the cache tags cache with the `grailsCacheManager` bean. A cache provider plugin replaces it by defining a bean of that name, and an application can do the same with a `GrailsCacheManager` of its own. -The annotations receive their cache manager by type. Where the application context has another cache manager too, Spring uses the one marked primary, and where none is, `grailsCacheManager`, also over one with a `@Priority`. That other cache manager might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. +The annotations receive their cache manager by type. Where the application context has another cache manager too, Spring uses the one marked primary, or the one with the highest `@Priority`, and where there is neither, `grailsCacheManager`. That other cache manager might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. A cache manager may have no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with. The annotated method then runs uncached, and a warning names the class and the cache once for each cache manager. diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index 4d15b6a49ed..95798a7576e 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -5008,8 +5008,6 @@ As of Grails 8.0.1, with `grails.plugin.springsecurity.rest.token.storage.jwt.us ==== A Second Cache Manager No Longer Stops a Cached Application From Starting -The cache annotations receive their cache manager by type. Grails 8.0.0 failed to start when the application context had a second `CacheManager` beside the plugin's `grailsCacheManager` and neither was marked primary, which is what happens when the Spring Security plugin's `cacheUsers` is set. Spring now uses `grailsCacheManager` there. Where one of them is marked primary, Spring uses that one, as before, and with caching turned off (`grails.cache.enabled: false`) nothing changes. This applies to classes compiled against Grails 8.0.0 too, so plugins need not be recompiled. - -One case changes: a cache manager with a `@Priority`, not marked primary, beside `grailsCacheManager`. The annotations used it in 8.0.0, and now use `grailsCacheManager`. Mark it primary to keep caching with it. +The cache annotations receive their cache manager by type. Grails 8.0.0 failed to start when the application context had a second `CacheManager` beside the plugin's `grailsCacheManager` and neither was marked primary or had a `@Priority`, which is what happens when the Spring Security plugin's `cacheUsers` is set. Spring now uses `grailsCacheManager` there. Where one of them is marked primary or has a `@Priority`, Spring uses that one, as before, and with caching turned off (`grails.cache.enabled: false`) nothing changes. This applies to classes compiled against Grails 8.0.0 too, so plugins need not be recompiled. Where the cache manager has no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with, the annotated method now runs uncached, and a warning names the class and the cache once. Grails 8.0.0 failed with a `NullPointerException` on each call. This applies to classes compiled against this version. diff --git a/grails-skills/upgrade/skills/grails-upgrade/SKILL.md b/grails-skills/upgrade/skills/grails-upgrade/SKILL.md index a7e51750d51..15e60cfb3dc 100644 --- a/grails-skills/upgrade/skills/grails-upgrade/SKILL.md +++ b/grails-skills/upgrade/skills/grails-upgrade/SKILL.md @@ -1666,8 +1666,7 @@ java -XX:MaxRAMPercentage=60.0 -XX:MaxMetaspaceSize=256m -Dgrails.env=prod -jar ## Cache Plugin Beside Another Cache Manager -- **A second `CacheManager` beside the cache plugin's `grailsCacheManager` no longer stops a cached application from starting.** Search for `CacheManager` beans the application or its plugins define, and for `cacheUsers` in the Spring Security plugin's configuration, which defines one named `cacheManager`. Where neither cache manager is marked primary, Grails 8.0.0 failed to create `grailsCacheAdminService` and every class with a cached method; Spring now uses `grailsCacheManager` there, also for classes compiled against 8.0.0. A cache manager marked primary is still used, and nothing changes with `grails.cache.enabled: false`. -- **A cache manager with a `@Priority`, not marked primary, beside `grailsCacheManager` is no longer used by the cache annotations.** Grails 8.0.0 used it. Mark it primary to keep caching with it. +- **A second `CacheManager` beside the cache plugin's `grailsCacheManager` no longer stops a cached application from starting.** Search for `CacheManager` beans the application or its plugins define, and for `cacheUsers` in the Spring Security plugin's configuration, which defines one named `cacheManager`. Where neither cache manager is marked primary or has a `@Priority`, Grails 8.0.0 failed to create `grailsCacheAdminService` and every class with a cached method; Spring now uses `grailsCacheManager` there, also for classes compiled against 8.0.0. A cache manager marked primary or with a `@Priority` is still used, and nothing changes with `grails.cache.enabled: false`. - **A method whose cache the cache manager does not have runs uncached.** A cache manager answers null for a cache name it has no cache of, as a `JCacheCacheManager` does for a cache it was not configured with, and in Grails 8.0.0 every call of such a `@Cacheable`, `@CachePut` or `@CacheEvict` method failed with a `NullPointerException`. Classes compiled against 8.0.1 run uncached there, and a warning names the class and the cache once. Configure the cache in that cache manager to cache with it. # After the Upgrade From eebd2bb8dc59898c92a280b2fd99802fc3893070 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 08:51:15 -0800 Subject: [PATCH 15/20] See the priority of a cache manager's object before the first injection The registrar reads the priority of the other cache managers from the types their definitions declare, as it runs before any bean exists. A factory method declared to return a CacheManager hides the priority of the object it returns, which Spring reads once that bean exists, so where such a cache manager was created before the first cache-aware bean, 8.0.0 injected it, and with the alias grailsCacheManager was taken instead. A grailsCacheManager created from a cache-aware bean then asked for itself while it was being created, and startup failed. With the alias, the registrar now adds a bean post-processor that runs the check again before the first cache-aware bean is injected, when the cache managers created by then have the type of their object, and removes the alias where one of them has a priority. It creates no bean, and it decides once, so every cache-aware bean gets the cache manager the first one gets. The matrix gains a cache manager declared as CacheManager whose object has a priority, so 511 arrangements; with the previous registrar, 24 of them got grailsCacheManager where 8.0.0 got that one. CacheAutoConfigurationSpec covers the startup failure with such a cache manager created first. --- .../GrailsCacheManagerAliasRegistrar.groovy | 66 +++++++++++++++---- .../cache/CacheAutoConfigurationSpec.groovy | 15 +++-- .../GrailsCacheManagerAliasMatrixSpec.groovy | 11 ++-- 3 files changed, 72 insertions(+), 20 deletions(-) diff --git a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy index c29a29fc9c0..451ba5b3dff 100644 --- a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy @@ -18,17 +18,22 @@ */ package org.grails.plugin.cache +import java.util.concurrent.atomic.AtomicBoolean + import groovy.transform.CompileStatic import groovy.util.logging.Slf4j import org.springframework.beans.BeansException +import org.springframework.beans.PropertyValues import org.springframework.beans.factory.BeanFactoryUtils import org.springframework.beans.factory.NoSuchBeanDefinitionException import org.springframework.beans.factory.config.BeanDefinition import org.springframework.beans.factory.config.BeanFactoryPostProcessor import org.springframework.beans.factory.config.ConfigurableListableBeanFactory +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor import org.springframework.beans.factory.support.AbstractBeanDefinition import org.springframework.cache.CacheManager +import org.springframework.core.AliasRegistry import org.springframework.core.annotation.OrderUtils /** @@ -45,10 +50,14 @@ import org.springframework.core.annotation.OrderUtils *

Spring takes a bean named like the field before one with a higher priority, so the alias is left * out where another cache manager is marked primary or has a priority, to keep Spring's choice there. * Otherwise a {@code grailsCacheManager} created from a cache-aware bean, which Spring gave the other - * cache manager, would be asked for while it is being created, and fail. The priority is read from the - * class of the bean as its definition declares it, as no bean is created here; a priority that only - * the created object has, behind a factory method declared to return a {@code CacheManager}, is not - * seen.

+ * cache manager, would be asked for while it is being created, and fail.

+ * + *

No bean is created here, so the priority is read from the type the bean definitions declare. A + * factory method declared to return a {@code CacheManager} hides the priority of the object it returns, + * which Spring reads once that bean exists. So the check runs again before the first cache-aware bean + * is injected, when the cache managers created by then have the type of their object, and the alias is + * removed where one of them has a priority. Spring sees the priority of the same cache managers when it + * injects that bean, and every cache-aware bean gets the same cache manager.

* *

The alias is registered after every bean definition is in, so a {@code grailsCacheManager} that a * cache provider plugin or the application defines gets it too, and it is registered only where there @@ -68,25 +77,32 @@ class GrailsCacheManagerAliasRegistrar implements BeanFactoryPostProcessor { @Override void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (beanFactory.containsBean(CACHE_MANAGER_BEAN_NAME) && !beanFactory.containsBean(ALIAS) && - !anotherPreferred(beanFactory)) { + !anotherPreferred(beanFactory, false)) { beanFactory.registerAlias(CACHE_MANAGER_BEAN_NAME, ALIAS) + beanFactory.addBeanPostProcessor(new PriorityOfCreatedCacheManagers(beanFactory)) } } - /** Whether Spring prefers another cache manager over {@code grailsCacheManager}, as primary or by priority. */ - private static boolean anotherPreferred(ConfigurableListableBeanFactory beanFactory) { + /** + * Whether Spring prefers another cache manager over {@code grailsCacheManager}, as primary or by priority. + * + * @param allowFactoryBeanInit whether a factory bean may be created to tell the type of its object, as + * Spring does when it injects + */ + private static boolean anotherPreferred(ConfigurableListableBeanFactory beanFactory, boolean allowFactoryBeanInit) { BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, CacheManager, true, false).any { String name -> name != CACHE_MANAGER_BEAN_NAME && !(CACHE_MANAGER_BEAN_NAME in beanFactory.getAliases(name)) && - preferredBySpring(beanFactory, name) + preferredBySpring(beanFactory, name, allowFactoryBeanInit) } } /** * Whether Spring prefers the cache manager when it injects one by type. One registered as a singleton * has no bean definition, and only the priority of its class. One that is not a candidate for - * injection by type is never preferred. + * injection by type is never preferred. The type of a cache manager that exists is that of its object. */ - private static boolean preferredBySpring(ConfigurableListableBeanFactory beanFactory, String name) { + private static boolean preferredBySpring(ConfigurableListableBeanFactory beanFactory, String name, + boolean allowFactoryBeanInit) { try { BeanDefinition definition = definitionOf(beanFactory, name) if (definition != null) { @@ -98,7 +114,7 @@ class GrailsCacheManagerAliasRegistrar implements BeanFactoryPostProcessor { return true } } - Class type = beanFactory.getType(name, false) + Class type = beanFactory.getType(name, allowFactoryBeanInit) return type != null && OrderUtils.getPriority(type) != null } catch (BeansException e) { @@ -116,4 +132,32 @@ class GrailsCacheManagerAliasRegistrar implements BeanFactoryPostProcessor { return null } } + + /** + * Before the first cache-aware bean is injected, removes the alias where a cache manager created by + * then has a priority its declared type did not show. It runs ahead of the injection, as it is added + * before the context registers its own bean post-processors, and only once, so that every cache-aware + * bean gets the cache manager the first one gets. + */ + @CompileStatic + private static class PriorityOfCreatedCacheManagers implements InstantiationAwareBeanPostProcessor { + + private final ConfigurableListableBeanFactory beanFactory + + private final AtomicBoolean checked = new AtomicBoolean() + + PriorityOfCreatedCacheManagers(ConfigurableListableBeanFactory beanFactory) { + this.beanFactory = beanFactory + } + + @Override + PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { + if (bean instanceof GrailsCacheManagerAware && checked.compareAndSet(false, true) && + anotherPreferred(beanFactory, true)) { + AliasRegistry aliases = (AliasRegistry) beanFactory + aliases.removeAlias(ALIAS) + } + return pvs + } + } } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 2f6f91f61b6..4111ff26be7 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -171,17 +171,22 @@ class CacheAutoConfigurationSpec extends Specification { given: 'the application\'s grailsCacheManager, created from a bean that has a cache manager injected itself' GrailsCacheManager mine = Mock(GrailsCacheManager) AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() - context.registerBean('grailsCacheManager', GrailsCacheManager, { -> - context.getBean(CacheAware) - mine - } as Supplier) + + and: 'the cache manager Spring prefers, created first' if (preferred == 'with a priority') { context.registerBean('preferredCacheManager', HighPriorityCacheManager) } + else if (preferred == 'with a priority only on the object its factory returns') { + context.registerBean('preferredCacheManager', CacheManager, { -> new HighPriorityCacheManager() } as Supplier) + } else { context.registerBean('preferredCacheManager', ConcurrentMapCacheManager, { BeanDefinition definition -> definition.primary = true } as BeanDefinitionCustomizer) } + context.registerBean('grailsCacheManager', GrailsCacheManager, { -> + context.getBean(CacheAware) + mine + } as Supplier) context.registerBean(CacheAware) context.register(CacheAutoConfiguration) @@ -196,7 +201,7 @@ class CacheAutoConfigurationSpec extends Specification { context.close() where: - preferred << ['with a priority', 'marked primary'] + preferred << ['with a priority', 'with a priority only on the object its factory returns', 'marked primary'] } void 'another cache manager in the context, such as the one Spring Security caches users with, is not taken for the Grails one'() { diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy index 4e4a7caaa53..f008b9e2ccd 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy @@ -51,7 +51,8 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType', 'cyclic'] - private static final List OTHER_KINDS = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', 'priority'] + private static final List OTHER_KINDS = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', + 'priority', 'priorityOnObject'] void 'the alias is the name the trait\'s field has in a class that implements it'() { expect: @@ -69,7 +70,7 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { Map was = run(row, false) Map now = run(row, true) boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy'] - boolean anotherPreferred = row.any { String name, String kind -> name != NAMED && kind in ['primary', 'priority'] } + boolean anotherPreferred = row.any { String name, String kind -> name != NAMED && kind in ['primary', 'priority', 'priorityOnObject'] } Object expected = (was.failed && namedUsable && !anotherPreferred) ? NAMED : (was.failed ? 'failed' : was.chosen) Object got = now.failed ? 'failed' : now.chosen List allowedToCreate = ((List) was.created) + [NAMED] @@ -152,7 +153,9 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { context.registerBean(name, String, { -> 'not a cache manager' } as Supplier) return } - Class type = kind == 'priority' ? HighPriorityCacheManager : ConcurrentMapCacheManager + Class type = kind in ['priority', 'priorityOnObject'] ? HighPriorityCacheManager : ConcurrentMapCacheManager + // declared as a plain CacheManager, as a factory method would declare it, so only the object has the priority + Class declared = kind == 'priorityOnObject' ? CacheManager : type Supplier supplier = { -> if (kind == 'cyclic') { context.getBean('probe') @@ -170,7 +173,7 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { bean.fallback = kind == 'fallback' bean.defaultCandidate = kind != 'notDefault' } as BeanDefinitionCustomizer - context.registerBean(name, (Class) type, supplier, customizer) + context.registerBean(name, (Class) declared, supplier, customizer) } BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer context.registerBean('probe', CacheAware, lazy) From 1047ebb6d6bb9442b4ddad410430ec197298b891 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 16:31:51 -0800 Subject: [PATCH 16/20] Fall back to grailsCacheManager where Spring cannot choose, in place of the alias The alias of grailsCacheManager made Spring take it by name before a cache manager with a higher priority, and the registrar's checks of the other cache managers' priorities ran before Spring chose: at bean factory post-processing, and before the first cache-aware bean was injected. A cache manager created later than that, as by a key generator injected into the same bean before its cache manager, or the product of a factory bean that names only CacheManager as its type, has a priority Spring sees when it chooses and the checks did not. There grailsCacheManager was taken where 8.0.0 took the other one, and a grailsCacheManager created from the cache-aware bean then asked for itself and failed startup. There is no alias now. GrailsCacheManagerFallback wraps the bean factory's autowire candidate resolver. When Spring resolves the trait's field, the resolver first runs Spring's own resolution of it, with a descriptor that creates no cache manager Spring would not create to compare them and that notes where Spring cannot choose. Where Spring can choose, the resolver steps aside and Spring resolves the field as it did, at that moment; only where Spring cannot choose and grailsCacheManager is one of the cache managers it cannot choose between is the field given grailsCacheManager. Any other injection of a cache manager is left alone. GrailsCacheManagerFallbackMatrixSpec, renamed from the alias matrix, gains a factory bean whose product has a priority and a cache manager with a priority that the key generator creates, so 777 arrangements; with the alias registrar 67 of them differed from 8.0.0. It also covers singletons without a bean definition, a cache manager injected into a field of the application's own, which still fails where Spring cannot choose, and installing the resolver once. CacheAutoConfigurationSpec covers both of the new cases through the auto-configuration, with a grailsCacheManager created from the cache-aware bean; both failed to start with the alias registrar. --- .../plugin/cache/CacheGrailsPlugin.groovy | 4 +- .../GrailsCacheManagerAliasRegistrar.groovy | 163 --------------- .../cache/GrailsCacheManagerFallback.groovy | 192 ++++++++++++++++++ .../cache/CacheAutoConfigurationSpec.groovy | 31 ++- .../plugin/cache/MissingCacheSpec.groovy | 4 +- ...ailsCacheManagerFallbackMatrixSpec.groovy} | 167 +++++++++++---- 6 files changed, 349 insertions(+), 212 deletions(-) delete mode 100644 grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy create mode 100644 grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy rename grails-cache/src/test/groovy/org/grails/plugin/cache/{GrailsCacheManagerAliasMatrixSpec.groovy => GrailsCacheManagerFallbackMatrixSpec.groovy} (54%) 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 202c5b5e74e..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,7 +28,7 @@ import org.springframework.cache.Cache import grails.plugins.Plugin import org.grails.plugin.cache.GrailsCacheManager -import org.grails.plugin.cache.GrailsCacheManagerAliasRegistrar +import org.grails.plugin.cache.GrailsCacheManagerFallback /** * Configures the cache plugin. @@ -83,7 +83,7 @@ class CacheGrailsPlugin extends Plugin { // 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(GrailsCacheManagerAliasRegistrar).staticMethod() + bean(GrailsCacheManagerFallback).staticMethod() bean(GrailsCacheManager).conditionalOnMissingBeanName() { CachePluginConfiguration grailsCacheConfiguration -> if (cacheManagerType == 'GrailsConcurrentLinkedMapCacheManager') { diff --git a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy deleted file mode 100644 index 451ba5b3dff..00000000000 --- a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasRegistrar.groovy +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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.atomic.AtomicBoolean - -import groovy.transform.CompileStatic -import groovy.util.logging.Slf4j - -import org.springframework.beans.BeansException -import org.springframework.beans.PropertyValues -import org.springframework.beans.factory.BeanFactoryUtils -import org.springframework.beans.factory.NoSuchBeanDefinitionException -import org.springframework.beans.factory.config.BeanDefinition -import org.springframework.beans.factory.config.BeanFactoryPostProcessor -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory -import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor -import org.springframework.beans.factory.support.AbstractBeanDefinition -import org.springframework.cache.CacheManager -import org.springframework.core.AliasRegistry -import org.springframework.core.annotation.OrderUtils - -/** - * Names the cache manager called {@code grailsCacheManager} after the field a cache-aware class has it - * injected into, so that Spring takes it where it cannot otherwise choose. - * - *

{@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. With this - * alias the renamed field matches {@code grailsCacheManager}. Where Spring could choose, which is the - * only cache manager, or one marked primary or with a priority, nothing changes.

- * - *

Spring takes a bean named like the field before one with a higher priority, so the alias is left - * out where another cache manager is marked primary or has a priority, to keep Spring's choice there. - * Otherwise a {@code grailsCacheManager} created from a cache-aware bean, which Spring gave the other - * cache manager, would be asked for while it is being created, and fail.

- * - *

No bean is created here, so the priority is read from the type the bean definitions declare. A - * factory method declared to return a {@code CacheManager} hides the priority of the object it returns, - * which Spring reads once that bean exists. So the check runs again before the first cache-aware bean - * is injected, when the cache managers created by then have the type of their object, and the alias is - * removed where one of them has a priority. Spring sees the priority of the same cache managers when it - * injects that bean, and every cache-aware bean gets the same cache manager.

- * - *

The alias is registered after every bean definition is in, so a {@code grailsCacheManager} that a - * cache provider plugin or the application defines gets it too, and it is registered only where there - * is a bean of that name and the alias is free.

- * - * @since 8.0.1 - */ -@Slf4j -@CompileStatic -class GrailsCacheManagerAliasRegistrar 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 ALIAS = "${GrailsCacheManagerAware.name.replace('.', '_')}__${CACHE_MANAGER_BEAN_NAME}".toString() - - @Override - void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - if (beanFactory.containsBean(CACHE_MANAGER_BEAN_NAME) && !beanFactory.containsBean(ALIAS) && - !anotherPreferred(beanFactory, false)) { - beanFactory.registerAlias(CACHE_MANAGER_BEAN_NAME, ALIAS) - beanFactory.addBeanPostProcessor(new PriorityOfCreatedCacheManagers(beanFactory)) - } - } - - /** - * Whether Spring prefers another cache manager over {@code grailsCacheManager}, as primary or by priority. - * - * @param allowFactoryBeanInit whether a factory bean may be created to tell the type of its object, as - * Spring does when it injects - */ - private static boolean anotherPreferred(ConfigurableListableBeanFactory beanFactory, boolean allowFactoryBeanInit) { - BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, CacheManager, true, false).any { String name -> - name != CACHE_MANAGER_BEAN_NAME && !(CACHE_MANAGER_BEAN_NAME in beanFactory.getAliases(name)) && - preferredBySpring(beanFactory, name, allowFactoryBeanInit) - } - } - - /** - * Whether Spring prefers the cache manager when it injects one by type. One registered as a singleton - * has no bean definition, and only the priority of its class. One that is not a candidate for - * injection by type is never preferred. The type of a cache manager that exists is that of its object. - */ - private static boolean preferredBySpring(ConfigurableListableBeanFactory beanFactory, String name, - boolean allowFactoryBeanInit) { - try { - BeanDefinition definition = definitionOf(beanFactory, name) - if (definition != null) { - if (!definition.autowireCandidate || - (definition instanceof AbstractBeanDefinition && !((AbstractBeanDefinition) definition).defaultCandidate)) { - return false - } - if (definition.primary) { - return true - } - } - Class type = beanFactory.getType(name, allowFactoryBeanInit) - return type != null && OrderUtils.getPriority(type) != null - } - catch (BeansException e) { - // a definition that cannot be read fails when its bean is created, not here - log.debug('Could not tell whether Spring prefers the cache manager {}', name, e) - return false - } - } - - private static BeanDefinition definitionOf(ConfigurableListableBeanFactory beanFactory, String name) { - try { - return beanFactory.getMergedBeanDefinition(name) - } - catch (NoSuchBeanDefinitionException ignored) { - return null - } - } - - /** - * Before the first cache-aware bean is injected, removes the alias where a cache manager created by - * then has a priority its declared type did not show. It runs ahead of the injection, as it is added - * before the context registers its own bean post-processors, and only once, so that every cache-aware - * bean gets the cache manager the first one gets. - */ - @CompileStatic - private static class PriorityOfCreatedCacheManagers implements InstantiationAwareBeanPostProcessor { - - private final ConfigurableListableBeanFactory beanFactory - - private final AtomicBoolean checked = new AtomicBoolean() - - PriorityOfCreatedCacheManagers(ConfigurableListableBeanFactory beanFactory) { - this.beanFactory = beanFactory - } - - @Override - PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { - if (bean instanceof GrailsCacheManagerAware && checked.compareAndSet(false, true) && - anotherPreferred(beanFactory, true)) { - AliasRegistry aliases = (AliasRegistry) beanFactory - aliases.removeAlias(ALIAS) - } - return pvs - } - } -} 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..bc038f612bd --- /dev/null +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy @@ -0,0 +1,192 @@ +/* + * 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 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.NoUniqueBeanDefinitionException +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.config.SingletonBeanRegistry +import org.springframework.beans.factory.support.AutowireCandidateResolver +import org.springframework.beans.factory.support.DefaultListableBeanFactory +import org.springframework.cache.CacheManager +import org.springframework.cache.support.NoOpCacheManager +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. When Spring resolves the trait's field, + * the resolver first runs Spring's own resolution of it, which creates no cache manager that Spring would + * not create to compare them. Where Spring can choose, the resolver steps aside, and Spring resolves the + * field as it did: the only cache manager, the one marked primary or the one with the highest priority, + * judged at that moment, with the objects of the cache managers created by then, the products of factory + * beans included. Only where Spring would fail because it cannot choose, and {@code grailsCacheManager} + * is one of the cache managers it cannot choose between, is the field given {@code grailsCacheManager}. + * Any other injection of a cache manager is left alone.

+ * + * @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, with the trait's field given {@code grailsCacheManager} where Spring + * cannot choose. + */ + @CompileStatic + static class CandidateResolver implements AutowireCandidateResolver, BeanFactoryAware { + + private final AutowireCandidateResolver delegate + + private ConfigurableListableBeanFactory beanFactory + + CandidateResolver(AutowireCandidateResolver delegate) { + this.delegate = delegate + } + + @Override + void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory instanceof ConfigurableListableBeanFactory ? + (ConfigurableListableBeanFactory) beanFactory : null + if (delegate instanceof BeanFactoryAware) { + ((BeanFactoryAware) delegate).beanFactory = beanFactory + } + } + + @Override + Object getSuggestedValue(DependencyDescriptor descriptor) { + Object suggested = delegate.getSuggestedValue(descriptor) + if (suggested != null || beanFactory == null || descriptor instanceof Probe || !isTraitField(descriptor)) { + return suggested + } + Probe probe = new Probe(descriptor) + try { + beanFactory.resolveDependency(probe, null) + } + catch (NoUniqueBeanDefinitionException ignored) { + // Spring rejects the candidates before it would fall back, as with two marked primary + return null + } + probe.cannotChooseBesideGrails ? beanFactory.getBean(CACHE_MANAGER_BEAN_NAME, CacheManager) : null + } + + @Override + boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { + delegate.isAutowireCandidate(bdHolder, descriptor) + } + + @Override + boolean isRequired(DependencyDescriptor descriptor) { + delegate.isRequired(descriptor) + } + + @Override + boolean hasQualifier(DependencyDescriptor descriptor) { + delegate.hasQualifier(descriptor) + } + + @Override + String getSuggestedName(DependencyDescriptor descriptor) { + delegate.getSuggestedName(descriptor) + } + + @Override + Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, String beanName) { + delegate.getLazyResolutionProxyIfNecessary(descriptor, beanName) + } + + @Override + Class getLazyResolutionProxyClass(DependencyDescriptor descriptor, String beanName) { + delegate.getLazyResolutionProxyClass(descriptor, beanName) + } + + @Override + AutowireCandidateResolver cloneIfNecessary() { + new CandidateResolver(delegate.cloneIfNecessary()) + } + } + + /** + * Spring's resolution of the trait's field, which tells whether Spring can choose. It creates the + * cache managers Spring creates to compare them, those that exist and the products of factory beans + * that exist, and not the one it would choose, which Spring creates when it resolves the field. + */ + @CompileStatic + private static class Probe extends DependencyDescriptor { + + /** Stands for the cache manager Spring would choose, which the probe does not create. */ + private static final CacheManager NOT_CREATED = new NoOpCacheManager() + + boolean cannotChooseBesideGrails + + Probe(DependencyDescriptor original) { + super(original) + } + + @Override + Object resolveNotUnique(ResolvableType type, Map matchingBeans) throws BeansException { + if (matchingBeans.containsKey(CACHE_MANAGER_BEAN_NAME)) { + cannotChooseBesideGrails = true + return NOT_CREATED + } + super.resolveNotUnique(type, matchingBeans) + } + + @Override + Object resolveCandidate(String beanName, Class requiredType, BeanFactory beanFactory) throws BeansException { + boolean exists = beanFactory instanceof SingletonBeanRegistry && + ((SingletonBeanRegistry) beanFactory).containsSingleton(beanName) + exists ? super.resolveCandidate(beanName, requiredType, beanFactory) : NOT_CREATED + } + } +} diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 4111ff26be7..88b5cba3ae8 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -24,6 +24,7 @@ import groovy.transform.CompileStatic import jakarta.annotation.Priority +import org.springframework.beans.factory.FactoryBean import org.springframework.beans.factory.config.BeanDefinition import org.springframework.beans.factory.config.BeanDefinitionCustomizer import org.springframework.cache.CacheManager @@ -179,6 +180,18 @@ class CacheAutoConfigurationSpec extends Specification { else if (preferred == 'with a priority only on the object its factory returns') { context.registerBean('preferredCacheManager', CacheManager, { -> new HighPriorityCacheManager() } as Supplier) } + else if (preferred == 'that a factory bean naming only CacheManager makes, with a priority') { + context.registerBean('preferredCacheManager', PriorityProductFactoryBean) + } + else if (preferred == 'with a priority, which the key generator creates as the cache-aware bean is injected') { + BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer + context.registerBean('preferredCacheManager', CacheManager, + { -> new HighPriorityCacheManager() } as Supplier, lazy) + context.registerBean('customCacheKeyGenerator', GrailsCacheKeyGenerator, { -> + context.getBean('preferredCacheManager') + new CustomCacheKeyGenerator() + } as Supplier, lazy) + } else { context.registerBean('preferredCacheManager', ConcurrentMapCacheManager, { BeanDefinition definition -> definition.primary = true } as BeanDefinitionCustomizer) @@ -201,7 +214,9 @@ class CacheAutoConfigurationSpec extends Specification { context.close() where: - preferred << ['with a priority', 'with a priority only on the object its factory returns', 'marked primary'] + preferred << ['with a priority', 'with a priority only on the object its factory returns', + 'that a factory bean naming only CacheManager makes, with a priority', + 'with a priority, which the key generator creates as the cache-aware bean is injected', 'marked primary'] } void 'another cache manager in the context, such as the one Spring Security caches users with, is not taken for the Grails one'() { @@ -289,6 +304,20 @@ class CacheAutoConfigurationSpec extends Specification { static class HighPriorityCacheManager extends ConcurrentMapCacheManager { } + /** A factory bean that names only CacheManager as its type, and makes a cache manager with a priority. */ + static class PriorityProductFactoryBean implements FactoryBean { + + @Override + CacheManager getObject() { + new HighPriorityCacheManager() + } + + @Override + Class getObjectType() { + CacheManager + } + } + /** A class the cache transformations make cache-aware, as they do a service with a cached method. */ static class CacheAware implements GrailsCacheManagerAware { } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy index 0a876a6a4b7..3b5c8944c66 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy @@ -29,7 +29,7 @@ import spock.lang.Specification import spock.lang.Unroll import org.apache.grails.core.testing.support.LogCapture -import org.grails.plugin.cache.GrailsCacheManagerAliasRegistrar +import org.grails.plugin.cache.GrailsCacheManagerFallback import org.grails.plugin.cache.MissingCacheReporter /** @@ -45,7 +45,7 @@ class MissingCacheSpec extends Specification { CacheManager cacheManager = new ConcurrentMapCacheManager('configured') GenericApplicationContext context = new GenericApplicationContext() AnnotationConfigUtils.registerAnnotationConfigProcessors(context) - context.addBeanFactoryPostProcessor(new GrailsCacheManagerAliasRegistrar()) + context.addBeanFactoryPostProcessor(new GrailsCacheManagerFallback()) context.registerBean('grailsCacheManager', CacheManager, { -> cacheManager } as Supplier) context.registerBean('cacheManager', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) context.registerBean('service', (Class) compile(mode)) diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy similarity index 54% rename from grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy rename to grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy index f008b9e2ccd..d69d83fcc56 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerAliasMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy @@ -23,40 +23,58 @@ import java.util.function.Supplier import jakarta.annotation.Priority import org.springframework.beans.BeansException +import org.springframework.beans.factory.FactoryBean +import org.springframework.beans.factory.NoUniqueBeanDefinitionException +import org.springframework.beans.factory.UnsatisfiedDependencyException +import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.BeanDefinition import org.springframework.beans.factory.config.BeanDefinitionCustomizer +import org.springframework.beans.factory.config.DependencyDescriptor import org.springframework.beans.factory.support.AbstractBeanDefinition +import org.springframework.beans.factory.support.AutowireCandidateResolver import org.springframework.cache.CacheManager import org.springframework.cache.concurrent.ConcurrentMapCacheManager import org.springframework.context.annotation.AnnotationConfigUtils import org.springframework.context.support.GenericApplicationContext import spock.lang.Specification +import grails.plugin.cache.CustomCacheKeyGenerator +import grails.plugin.cache.GrailsCacheKeyGenerator + /** - * Which cache manager a cache-aware class is injected with, with the alias of {@code grailsCacheManager}, + * Which cache manager a cache-aware class is injected with, with the fallback to {@code grailsCacheManager}, * against the oracle of 8.0.0: the same class, in the same context, without it. * *

The matrix crosses the ways a bean named {@code grailsCacheManager} can be defined with none, one * or two other cache managers, each defined in one of the ways a bean is chosen or passed over for * injection. One way to define {@code grailsCacheManager} creates it from the cache-aware bean, which so - * has a cache manager injected while {@code grailsCacheManager} is being created. The one deliberate + * has a cache manager injected while {@code grailsCacheManager} is being created. Of the other cache + * managers, some have a priority Spring sees only on their object: one declared as a plain + * {@code CacheManager}, the product of a factory bean that names only {@code CacheManager} as its type, + * and one the cache-aware bean's key generator creates while that bean is injected. The one deliberate * difference: where Spring could not choose, which failed startup, the class gets - * {@code grailsCacheManager}, unless another cache manager is marked primary or has a priority, where - * Spring's choice is left as it was. Otherwise the choice, and every failure, is 8.0.0's, and no cache + * {@code grailsCacheManager}, unless another cache manager is preferred, as primary or by priority, where + * Spring rejects the tie itself. Otherwise the choice, and every failure, is 8.0.0's, and no cache * manager is created that 8.0.0 did not create, other than {@code grailsCacheManager}.

*/ -class GrailsCacheManagerAliasMatrixSpec extends Specification { +class GrailsCacheManagerFallbackMatrixSpec extends Specification { - private static final String NAMED = GrailsCacheManagerAliasRegistrar.CACHE_MANAGER_BEAN_NAME + private static final String NAMED = GrailsCacheManagerFallback.CACHE_MANAGER_BEAN_NAME private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType', 'cyclic'] private static final List OTHER_KINDS = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', - 'priority', 'priorityOnObject'] + 'priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator'] + + private static final List PREFERRED_KINDS = ['primary', 'priority', 'priorityOnObject', 'factoryBean', + 'createdByKeyGenerator'] - void 'the alias is the name the trait\'s field has in a class that implements it'() { + void 'the fallback applies to the field the trait has in a class that implements it'() { expect: - CacheAware.declaredFields*.name.contains(GrailsCacheManagerAliasRegistrar.ALIAS) + CacheAware.declaredFields*.name.contains(GrailsCacheManagerFallback.FIELD_NAME) + GrailsCacheManagerFallback.isTraitField(new DependencyDescriptor( + CacheAware.getDeclaredField(GrailsCacheManagerFallback.FIELD_NAME), false)) + !GrailsCacheManagerFallback.isTraitField(new DependencyDescriptor(OwnInjection.getDeclaredField('someCacheManager'), false)) } void 'the cache manager a cache-aware class gets is 8.0.0\'s, except where it failed with none preferred'() { @@ -64,13 +82,13 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { List> rows = arrangements() assert rows.size() == NAMED_KINDS.size() * (1 + OTHER_KINDS.size() + OTHER_KINDS.size() * OTHER_KINDS.size()) - expect: 'every arrangement, each in a context of its own, with the alias and without it' + expect: 'every arrangement, each in a context of its own, with the fallback and without it' List mismatches = [] rows.each { Map row -> Map was = run(row, false) Map now = run(row, true) boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy'] - boolean anotherPreferred = row.any { String name, String kind -> name != NAMED && kind in ['primary', 'priority', 'priorityOnObject'] } + boolean anotherPreferred = row.any { String name, String kind -> name != NAMED && kind in PREFERRED_KINDS } Object expected = (was.failed && namedUsable && !anotherPreferred) ? NAMED : (was.failed ? 'failed' : was.chosen) Object got = now.failed ? 'failed' : now.chosen List allowedToCreate = ((List) was.created) + [NAMED] @@ -84,41 +102,61 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { mismatches == [] } - void 'no alias is registered where there is no grailsCacheManager, where its name is taken, or beside a preferred singleton'() { + void 'cache managers registered as singletons, without a bean definition, are judged as Spring judges them'() { given: - GenericApplicationContext withNone = context([first: 'plain'], [:], [], true) - GenericApplicationContext taken = context([(NAMED): 'plain'], [:], [], false) - taken.beanFactory.registerAlias('first', GrailsCacheManagerAliasRegistrar.ALIAS) - taken.registerBean('first', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) + CacheManager preferred = new HighPriorityCacheManager() + GenericApplicationContext besidePriority = context([(NAMED): 'plain'], [:], [], true) { GenericApplicationContext it -> + it.beanFactory.registerSingleton('preferred', preferred) + } + GenericApplicationContext besidePlain = context([(NAMED): 'plain'], [:], [], true) { GenericApplicationContext it -> + it.beanFactory.registerSingleton('other', new ConcurrentMapCacheManager()) + } - and: 'cache managers registered as singletons, which have no bean definition, one of a class with a priority' - GenericApplicationContext besidePriority = context([(NAMED): 'plain'], [:], [], false) - besidePriority.beanFactory.registerSingleton('preferred', new HighPriorityCacheManager()) - GenericApplicationContext besidePlain = context([(NAMED): 'plain'], [:], [], false) - besidePlain.beanFactory.registerSingleton('other', new ConcurrentMapCacheManager()) + expect: 'the one with a priority, as Spring chooses it, and grailsCacheManager where Spring cannot choose' + besidePriority.getBean('probe', CacheAware).grailsCacheManager.is(preferred) + besidePlain.getBean('probe', CacheAware).grailsCacheManager.is(besidePlain.getBean(NAMED)) - when: - [taken, besidePriority, besidePlain].each { GenericApplicationContext context -> - new GrailsCacheManagerAliasRegistrar().postProcessBeanFactory(context.beanFactory) + cleanup: + besidePriority?.close() + besidePlain?.close() + } + + void 'a cache manager injected anywhere else is left as Spring resolves it'() { + given: 'two cache managers Spring cannot choose between, and a bean of the application\'s own that injects one' + GenericApplicationContext context = context([(NAMED): 'plain', first: 'plain'], [:], [], true) { GenericApplicationContext it -> + it.registerBean('own', OwnInjection, { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer) } - then: - !withNone.beanFactory.isAlias(GrailsCacheManagerAliasRegistrar.ALIAS) - taken.beanFactory.getAliases('first').contains(GrailsCacheManagerAliasRegistrar.ALIAS) - !taken.beanFactory.getAliases(NAMED).contains(GrailsCacheManagerAliasRegistrar.ALIAS) - !besidePriority.beanFactory.isAlias(GrailsCacheManagerAliasRegistrar.ALIAS) + when: + context.getBean('own') - and: 'a singleton without a priority leaves the alias to be registered' - besidePlain.beanFactory.getAliases(NAMED).contains(GrailsCacheManagerAliasRegistrar.ALIAS) + then: 'it fails as it did, while the cache-aware class gets grailsCacheManager' + UnsatisfiedDependencyException e = thrown() + e.cause instanceof NoUniqueBeanDefinitionException + context.getBean('probe', CacheAware).grailsCacheManager.is(context.getBean(NAMED)) cleanup: - withNone?.close() - taken?.close() - besidePriority?.close() - besidePlain?.close() + context?.close() + } + + void 'the resolver is installed once, and a copy of it falls back too'() { + given: + GenericApplicationContext context = context([(NAMED): 'plain'], [:], [], true) + + when: 'post-processed again, as a parent and child context sharing it would be' + new GrailsCacheManagerFallback().postProcessBeanFactory(context.beanFactory) + AutowireCandidateResolver resolver = context.defaultListableBeanFactory.autowireCandidateResolver + + then: + resolver instanceof GrailsCacheManagerFallback.CandidateResolver + !(resolver.@delegate instanceof GrailsCacheManagerFallback.CandidateResolver) + resolver.cloneIfNecessary() instanceof GrailsCacheManagerFallback.CandidateResolver + + cleanup: + context?.close() } - private Map run(Map row, boolean withAlias) { + private Map run(Map row, boolean withFallback) { Map instances = [:] List created = [] List atStartup = [] @@ -126,7 +164,7 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { GenericApplicationContext started = null try { // a cyclic grailsCacheManager has the probe injected while the context starts - started = context(row, instances, created, withAlias) + started = context(row, instances, created, withFallback) atStartup.addAll(created) CacheManager chosen = ((CacheAware) started.getBean('probe')).grailsCacheManager result.chosen = chosen == null ? null : instances.find { String name, CacheManager instance -> instance.is(chosen) }?.key @@ -142,20 +180,20 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { } private GenericApplicationContext context(Map row, Map instances, - List created, boolean withAlias) { + List created, boolean withFallback, + Closure beforeRefresh = null) { GenericApplicationContext context = new GenericApplicationContext() AnnotationConfigUtils.registerAnnotationConfigProcessors(context) - if (withAlias) { - context.addBeanFactoryPostProcessor(new GrailsCacheManagerAliasRegistrar()) + if (withFallback) { + context.addBeanFactoryPostProcessor(new GrailsCacheManagerFallback()) } row.each { String name, String kind -> if (kind == 'wrongType') { context.registerBean(name, String, { -> 'not a cache manager' } as Supplier) return } - Class type = kind in ['priority', 'priorityOnObject'] ? HighPriorityCacheManager : ConcurrentMapCacheManager - // declared as a plain CacheManager, as a factory method would declare it, so only the object has the priority - Class declared = kind == 'priorityOnObject' ? CacheManager : type + Class type = kind in ['priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator'] ? + HighPriorityCacheManager : ConcurrentMapCacheManager Supplier supplier = { -> if (kind == 'cyclic') { context.getBean('probe') @@ -165,10 +203,16 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { instances[name] = instance instance } as Supplier + if (kind == 'factoryBean') { + context.registerBean(name, ProductFactoryBean, { -> new ProductFactoryBean(supplier) } as Supplier) + return + } + // declared as a plain CacheManager, as a factory method would declare it, so only the object has the priority + Class declared = kind in ['priorityOnObject', 'createdByKeyGenerator'] ? CacheManager : type BeanDefinitionCustomizer customizer = { BeanDefinition definition -> AbstractBeanDefinition bean = (AbstractBeanDefinition) definition bean.primary = kind == 'primary' - bean.lazyInit = kind == 'lazy' + bean.lazyInit = kind in ['lazy', 'createdByKeyGenerator'] bean.autowireCandidate = kind != 'notCandidate' bean.fallback = kind == 'fallback' bean.defaultCandidate = kind != 'notDefault' @@ -176,7 +220,16 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { context.registerBean(name, (Class) declared, supplier, customizer) } BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer + List forKeyGenerator = row.findAll { String name, String kind -> kind == 'createdByKeyGenerator' }*.key + if (forKeyGenerator) { + // injected into the cache-aware bean before its cache manager, and creating cache managers when it is + context.registerBean('customCacheKeyGenerator', GrailsCacheKeyGenerator, { -> + forKeyGenerator.each { String name -> context.getBean(name) } + new CustomCacheKeyGenerator() + } as Supplier, lazy) + } context.registerBean('probe', CacheAware, lazy) + beforeRefresh?.call(context) context.refresh() context } @@ -193,7 +246,33 @@ class GrailsCacheManagerAliasMatrixSpec extends Specification { static class CacheAware implements GrailsCacheManagerAware { } + /** A bean of the application's own that injects a cache manager by type, as the trait does. */ + static class OwnInjection { + @Autowired(required = false) + CacheManager someCacheManager + } + @Priority(1) static class HighPriorityCacheManager extends ConcurrentMapCacheManager { } + + /** A factory bean that names only CacheManager as its type, and makes a cache manager with a priority. */ + static class ProductFactoryBean implements FactoryBean { + + private final Supplier product + + ProductFactoryBean(Supplier product) { + this.product = product + } + + @Override + CacheManager getObject() { + product.get() + } + + @Override + Class getObjectType() { + CacheManager + } + } } From 5b6bfc772ee8b7d790eaf4a2a55a8c5bc8e17784 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 17:31:50 -0800 Subject: [PATCH 17/20] Resolve the trait's field once, for the bean being injected The fallback resolved the trait's field twice: a probe of Spring's own resolution without the requesting bean, then, where Spring could choose, the injection's own, and where it could not, the fallback's value through getSuggestedValue. Without the requesting bean, the probe did not leave the bean out of its own candidates, so a grailsCacheManager that is cache-aware itself was injected into itself, or with circular references disallowed failed to start, where 8.0.0 gave it the other cache manager. A factory bean of new cache managers made one for the probe and another for the injection. A suggested value is returned before Spring records the bean it injects, so the cache-aware bean was not registered as depending on grailsCacheManager, and could stop after it. The resolver now answers the field from getLazyResolutionProxyIfNecessary, which Spring asks with the requesting bean right before it would resolve the field, with the field's one resolution: Spring's doResolveDependency for that bean, with a descriptor that takes grailsCacheManager where Spring cannot choose. It registers the bean as depending on the cache managers that resolution took, as the injection registers it. The matrix gains a grailsCacheManager that is cache-aware itself and a factory bean of new cache managers, so 1,064 arrangements, and each row now also checks what such a grailsCacheManager gets, the beans the cache-aware bean depends on, and how many of each cache manager are created; with the previous fallback 233 rows failed them. CacheAutoConfigurationSpec covers a cache-aware grailsCacheManager with circular references allowed and disallowed, and the stop order of a cache-aware bean given grailsCacheManager. --- .../cache/GrailsCacheManagerFallback.groovy | 94 +++++++++--------- .../cache/CacheAutoConfigurationSpec.groovy | 98 +++++++++++++++++++ ...railsCacheManagerFallbackMatrixSpec.groovy | 91 +++++++++++++---- 3 files changed, 214 insertions(+), 69 deletions(-) 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 index bc038f612bd..12556beba24 100644 --- a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy @@ -23,16 +23,13 @@ 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.NoUniqueBeanDefinitionException 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.config.SingletonBeanRegistry import org.springframework.beans.factory.support.AutowireCandidateResolver import org.springframework.beans.factory.support.DefaultListableBeanFactory import org.springframework.cache.CacheManager -import org.springframework.cache.support.NoOpCacheManager import org.springframework.core.ResolvableType /** @@ -44,14 +41,15 @@ import org.springframework.core.ResolvableType * 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. When Spring resolves the trait's field, - * the resolver first runs Spring's own resolution of it, which creates no cache manager that Spring would - * not create to compare them. Where Spring can choose, the resolver steps aside, and Spring resolves the - * field as it did: the only cache manager, the one marked primary or the one with the highest priority, - * judged at that moment, with the objects of the cache managers created by then, the products of factory - * beans included. Only where Spring would fail because it cannot choose, and {@code grailsCacheManager} - * is one of the cache managers it cannot choose between, is the field given {@code grailsCacheManager}. - * Any other injection of a cache manager is left alone.

+ *

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}. 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. The bean is registered as depending on the cache + * managers the resolution took, as the injection registers it. Any other injection of a cache manager is + * left alone.

* * @since 8.0.1 */ @@ -80,15 +78,15 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { } /** - * The bean factory's resolver, with the trait's field given {@code grailsCacheManager} where Spring - * cannot choose. + * 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 ConfigurableListableBeanFactory beanFactory + private DefaultListableBeanFactory beanFactory CandidateResolver(AutowireCandidateResolver delegate) { this.delegate = delegate @@ -96,28 +94,33 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { @Override void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory instanceof ConfigurableListableBeanFactory ? - (ConfigurableListableBeanFactory) beanFactory : null + this.beanFactory = beanFactory instanceof DefaultListableBeanFactory ? (DefaultListableBeanFactory) beanFactory : null if (delegate instanceof BeanFactoryAware) { ((BeanFactoryAware) delegate).beanFactory = beanFactory } } @Override - Object getSuggestedValue(DependencyDescriptor descriptor) { - Object suggested = delegate.getSuggestedValue(descriptor) - if (suggested != null || beanFactory == null || descriptor instanceof Probe || !isTraitField(descriptor)) { - return suggested + Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, String beanName) { + Object proxy = delegate.getLazyResolutionProxyIfNecessary(descriptor, beanName) + if (proxy != null || beanFactory == null || descriptor instanceof FallbackDescriptor || !isTraitField(descriptor)) { + return proxy } - Probe probe = new Probe(descriptor) - try { - beanFactory.resolveDependency(probe, null) + FallbackDescriptor fallback = new FallbackDescriptor(descriptor, beanFactory) + Set autowiredBeanNames = new LinkedHashSet() + Object value = beanFactory.doResolveDependency(fallback, beanName, autowiredBeanNames, null) + if (fallback.fellBack) { + autowiredBeanNames << CACHE_MANAGER_BEAN_NAME } - catch (NoUniqueBeanDefinitionException ignored) { - // Spring rejects the candidates before it would fall back, as with two marked primary - return null + if (beanName != null) { + // as the injection registers the bean it injects, which this answer takes the place of + for (String autowiredBeanName : autowiredBeanNames) { + if (beanFactory.containsBean(autowiredBeanName)) { + beanFactory.registerDependentBean(autowiredBeanName, beanName) + } + } } - probe.cannotChooseBesideGrails ? beanFactory.getBean(CACHE_MANAGER_BEAN_NAME, CacheManager) : null + return value } @Override @@ -141,8 +144,8 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { } @Override - Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, String beanName) { - delegate.getLazyResolutionProxyIfNecessary(descriptor, beanName) + Object getSuggestedValue(DependencyDescriptor descriptor) { + delegate.getSuggestedValue(descriptor) } @Override @@ -156,37 +159,28 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { } } - /** - * Spring's resolution of the trait's field, which tells whether Spring can choose. It creates the - * cache managers Spring creates to compare them, those that exist and the products of factory beans - * that exist, and not the one it would choose, which Spring creates when it resolves the field. - */ + /** The trait's field, falling back to {@code grailsCacheManager} where Spring cannot choose. */ @CompileStatic - private static class Probe extends DependencyDescriptor { + private static class FallbackDescriptor extends DependencyDescriptor { - /** Stands for the cache manager Spring would choose, which the probe does not create. */ - private static final CacheManager NOT_CREATED = new NoOpCacheManager() + private final BeanFactory beanFactory - boolean cannotChooseBesideGrails + boolean fellBack - Probe(DependencyDescriptor original) { + FallbackDescriptor(DependencyDescriptor original, BeanFactory beanFactory) { super(original) + this.beanFactory = beanFactory } @Override Object resolveNotUnique(ResolvableType type, Map matchingBeans) throws BeansException { - if (matchingBeans.containsKey(CACHE_MANAGER_BEAN_NAME)) { - cannotChooseBesideGrails = true - return NOT_CREATED + if (!matchingBeans.containsKey(CACHE_MANAGER_BEAN_NAME)) { + return super.resolveNotUnique(type, matchingBeans) } - super.resolveNotUnique(type, matchingBeans) - } - - @Override - Object resolveCandidate(String beanName, Class requiredType, BeanFactory beanFactory) throws BeansException { - boolean exists = beanFactory instanceof SingletonBeanRegistry && - ((SingletonBeanRegistry) beanFactory).containsSingleton(beanName) - exists ? super.resolveCandidate(beanName, requiredType, beanFactory) : NOT_CREATED + fellBack = true + Object candidate = matchingBeans.get(CACHE_MANAGER_BEAN_NAME) + // created here if it is not yet, as Spring creates the candidate it chooses + candidate instanceof Class ? resolveCandidate(CACHE_MANAGER_BEAN_NAME, CacheManager, beanFactory) : candidate } } } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 88b5cba3ae8..6a41540f1e4 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -29,6 +29,7 @@ import org.springframework.beans.factory.config.BeanDefinition import org.springframework.beans.factory.config.BeanDefinitionCustomizer import org.springframework.cache.CacheManager import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import org.springframework.context.SmartLifecycle import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.core.env.MapPropertySource @@ -219,6 +220,54 @@ class CacheAutoConfigurationSpec extends Specification { 'with a priority, which the key generator creates as the cache-aware bean is injected', 'marked primary'] } + @Unroll + void 'a grailsCacheManager that is cache-aware itself gets the other cache manager, as in 8.0.0, with circular references #circular'() { + given: 'Spring leaves a bean out of the candidates for its own fields' + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() + context.allowCircularReferences = circular == 'allowed' + context.registerBean('grailsCacheManager', CacheAwareGrailsCacheManager) + CacheManager other = new ConcurrentMapCacheManager() + context.registerBean('other', CacheManager, { -> other } as Supplier) + context.registerBean(CacheAware) + context.register(CacheAutoConfiguration) + + when: + context.refresh() + + then: 'it starts, and grailsCacheManager is not given itself' + context.getBean('grailsCacheManager', GrailsCacheManagerAware).grailsCacheManager.is(other) + + and: 'a cache-aware bean beside both, where Spring cannot choose, gets grailsCacheManager' + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('grailsCacheManager')) + + cleanup: + context.close() + + where: + circular << ['allowed', 'not allowed'] + } + + void 'a cache-aware bean given grailsCacheManager depends on it, so it stops while that cache manager still runs'() { + given: 'a grailsCacheManager stopped in a later phase than the cache-aware bean, and another cache manager' + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() + context.registerBean('grailsCacheManager', LifecycleGrailsCacheManager) + context.registerBean('cacheManager', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) + context.registerBean('service', LifecycleService) + context.register(CacheAutoConfiguration) + context.refresh() + LifecycleService service = context.getBean('service', LifecycleService) + + expect: 'it is given grailsCacheManager, and registered as depending on it, as an injection registers it' + service.grailsCacheManager.is(context.getBean('grailsCacheManager')) + 'service' in context.beanFactory.getDependentBeans('grailsCacheManager') + + when: + context.close() + + then: 'it stops first, while grailsCacheManager still runs' + service.stoppedWhileCacheManagerRan + } + void 'another cache manager in the context, such as the one Spring Security caches users with, is not taken for the Grails one'() { given: 'Spring Security defines cacheManager when cacheUsers is set' CacheManager other = new ConcurrentMapCacheManager() @@ -318,6 +367,55 @@ class CacheAutoConfigurationSpec extends Specification { } } + /** A grailsCacheManager that is cache-aware itself. */ + static class CacheAwareGrailsCacheManager extends GrailsConcurrentMapCacheManager implements GrailsCacheManagerAware { + } + + /** A grailsCacheManager with a lifecycle, stopped in a later phase than {@link LifecycleService}. */ + static class LifecycleGrailsCacheManager extends GrailsConcurrentMapCacheManager implements SmartLifecycle { + + boolean running + + @Override + void start() { + running = true + } + + @Override + void stop() { + running = false + } + + @Override + int getPhase() { + 100 + } + } + + /** A cache-aware bean with a lifecycle, which records whether its cache manager ran when it stopped. */ + static class LifecycleService implements GrailsCacheManagerAware, SmartLifecycle { + + boolean running + + boolean stoppedWhileCacheManagerRan + + @Override + void start() { + running = true + } + + @Override + void stop() { + stoppedWhileCacheManagerRan = ((LifecycleGrailsCacheManager) grailsCacheManager).running + running = false + } + + @Override + int getPhase() { + 0 + } + } + /** A class the cache transformations make cache-aware, as they do a service with a cached method. */ static class CacheAware implements GrailsCacheManagerAware { } diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy index d69d83fcc56..ef7031606a0 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy @@ -48,23 +48,27 @@ import grails.plugin.cache.GrailsCacheKeyGenerator *

The matrix crosses the ways a bean named {@code grailsCacheManager} can be defined with none, one * or two other cache managers, each defined in one of the ways a bean is chosen or passed over for * injection. One way to define {@code grailsCacheManager} creates it from the cache-aware bean, which so - * has a cache manager injected while {@code grailsCacheManager} is being created. Of the other cache + * has a cache manager injected while {@code grailsCacheManager} is being created, and another makes it + * cache-aware itself, which Spring leaves out of its own candidates. Of the other cache * managers, some have a priority Spring sees only on their object: one declared as a plain * {@code CacheManager}, the product of a factory bean that names only {@code CacheManager} as its type, - * and one the cache-aware bean's key generator creates while that bean is injected. The one deliberate + * and one the cache-aware bean's key generator creates while that bean is injected; another is a factory + * bean that makes a new cache manager each time it is asked. The one deliberate * difference: where Spring could not choose, which failed startup, the class gets * {@code grailsCacheManager}, unless another cache manager is preferred, as primary or by priority, where - * Spring rejects the tie itself. Otherwise the choice, and every failure, is 8.0.0's, and no cache - * manager is created that 8.0.0 did not create, other than {@code grailsCacheManager}.

+ * Spring rejects the tie itself. Otherwise the choice, and every failure, is 8.0.0's: what the cache-aware + * bean and a cache-aware {@code grailsCacheManager} get, the beans the cache-aware bean is registered as + * depending on, and how many of each cache manager are created, other than {@code grailsCacheManager}.

*/ class GrailsCacheManagerFallbackMatrixSpec extends Specification { private static final String NAMED = GrailsCacheManagerFallback.CACHE_MANAGER_BEAN_NAME - private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType', 'cyclic'] + private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType', 'cyclic', + 'cacheAware'] private static final List OTHER_KINDS = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', - 'priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator'] + 'priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator', 'prototypeFactoryBean'] private static final List PREFERRED_KINDS = ['primary', 'priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator'] @@ -87,17 +91,28 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { rows.each { Map row -> Map was = run(row, false) Map now = run(row, true) - boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy'] + boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy', 'cacheAware'] boolean anotherPreferred = row.any { String name, String kind -> name != NAMED && kind in PREFERRED_KINDS } - Object expected = (was.failed && namedUsable && !anotherPreferred) ? NAMED : (was.failed ? 'failed' : was.chosen) + // a context that does not start has failed before the cache-aware bean, where it cannot fall back + boolean fallsBack = was.failed && !was.failedAtStartup && namedUsable && !anotherPreferred + Object expected = fallsBack ? NAMED : (was.failed ? 'failed' : was.chosen) Object got = now.failed ? 'failed' : now.chosen - List allowedToCreate = ((List) was.created) + [NAMED] + Map wasCreated = ((List) was.created).countBy { it } + String overCreated = ((List) now.created).countBy { it }.find { String name, Integer count -> + count > (wasCreated[name] ?: 0) + (name == NAMED ? 1 : 0) + }?.key if (got != expected) { mismatches << "${row}: got ${got}, expected ${expected} (8.0.0: ${was.failed ? 'failed' : was.chosen})".toString() } - else if (!allowedToCreate.containsAll((List) now.created)) { + else if (overCreated) { mismatches << "${row}: created ${now.created}, where 8.0.0 created ${was.created}".toString() } + else if (!now.failed && !was.failed && now.self != was.self) { + mismatches << "${row}: grailsCacheManager got ${now.self}, where in 8.0.0 it got ${was.self}".toString() + } + else if (!now.failed && (fallsBack ? !(NAMED in (List) now.dependencies) : now.dependencies != was.dependencies)) { + mismatches << "${row}: depends on ${now.dependencies}, where 8.0.0 depended on ${was.dependencies}".toString() + } } mismatches == [] } @@ -121,6 +136,17 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { besidePlain?.close() } + void 'a factory bean of new cache managers makes one for the injection, as in 8.0.0'() { + given: 'such a factory created first, beside a grailsCacheManager marked primary' + Map was = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], false) + Map now = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], true) + + expect: 'it is asked once, with the fallback as without it, and grailsCacheManager is injected' + ((List) was.created).count('factory') == 1 + ((List) now.created).count('factory') == 1 + now.chosen == NAMED && was.chosen == NAMED + } + void 'a cache manager injected anywhere else is left as Spring resolves it'() { given: 'two cache managers Spring cannot choose between, and a bean of the application\'s own that injects one' GenericApplicationContext context = context([(NAMED): 'plain', first: 'plain'], [:], [], true) { GenericApplicationContext it -> @@ -160,14 +186,24 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { Map instances = [:] List created = [] List atStartup = [] - Map result = [failed: false] + Map result = [failed: false, failedAtStartup: false] GenericApplicationContext started = null try { - // a cyclic grailsCacheManager has the probe injected while the context starts - started = context(row, instances, created, withFallback) + try { + // a cyclic grailsCacheManager has the probe injected while the context starts + started = context(row, instances, created, withFallback) + } + catch (BeansException e) { + result.failedAtStartup = true + throw e + } atStartup.addAll(created) CacheManager chosen = ((CacheAware) started.getBean('probe')).grailsCacheManager - result.chosen = chosen == null ? null : instances.find { String name, CacheManager instance -> instance.is(chosen) }?.key + result.chosen = nameOf(chosen, instances) + if (row[NAMED] == 'cacheAware') { + result.self = nameOf(((GrailsCacheManagerAware) started.getBean(NAMED)).grailsCacheManager, instances) + } + result.dependencies = (started.beanFactory.getDependenciesForBean('probe') as List).sort() } catch (BeansException ignored) { result.failed = true @@ -179,6 +215,10 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { result } + private static String nameOf(CacheManager cacheManager, Map instances) { + cacheManager == null ? null : instances.find { String name, CacheManager instance -> instance.is(cacheManager) }?.key + } + private GenericApplicationContext context(Map row, Map instances, List created, boolean withFallback, Closure beforeRefresh = null) { @@ -193,7 +233,7 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { return } Class type = kind in ['priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator'] ? - HighPriorityCacheManager : ConcurrentMapCacheManager + HighPriorityCacheManager : (kind == 'cacheAware' ? CacheAwareCacheManager : ConcurrentMapCacheManager) Supplier supplier = { -> if (kind == 'cyclic') { context.getBean('probe') @@ -203,8 +243,9 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { instances[name] = instance instance } as Supplier - if (kind == 'factoryBean') { - context.registerBean(name, ProductFactoryBean, { -> new ProductFactoryBean(supplier) } as Supplier) + if (kind in ['factoryBean', 'prototypeFactoryBean']) { + boolean singleton = kind == 'factoryBean' + context.registerBean(name, ProductFactoryBean, { -> new ProductFactoryBean(supplier, singleton) } as Supplier) return } // declared as a plain CacheManager, as a factory method would declare it, so only the object has the priority @@ -256,13 +297,25 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { static class HighPriorityCacheManager extends ConcurrentMapCacheManager { } - /** A factory bean that names only CacheManager as its type, and makes a cache manager with a priority. */ + /** A grailsCacheManager that is cache-aware itself, which Spring leaves out of the candidates for its own field. */ + static class CacheAwareCacheManager extends ConcurrentMapCacheManager implements GrailsCacheManagerAware { + } + + /** A factory bean that names only CacheManager as its type, making one cache manager or a new one each time. */ static class ProductFactoryBean implements FactoryBean { private final Supplier product - ProductFactoryBean(Supplier product) { + private final boolean singleton + + ProductFactoryBean(Supplier product, boolean singleton) { this.product = product + this.singleton = singleton + } + + @Override + boolean isSingleton() { + singleton } @Override From 24e9f70ae8d65543ed89b58965c620f997d49fc0 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 18:14:08 -0800 Subject: [PATCH 18/20] Remember the cache manager a cache-aware bean was given, as the injection does After a field's first resolution picks one bean, Spring's injection remembers that bean's name and resolves the field by it from then on, so a prototype bean's next instances only fetch that bean. The fallback answers the trait's field itself, so Spring recorded no bean and kept only the descriptor, and every instance resolved the field afresh: a factory bean of new cache managers among the candidates made one for each instance, where 8.0.0 made one for the first. The resolver now remembers, by bean name and injection point, the cache manager the field took, where the injection would remember it: one bean, of the field's type. A later resolution of that field takes it by name, as long as it is still there and of that type. The matrix also creates three instances of a prototype cache-aware bean in each arrangement, and checks what they get and the cache managers they create against 8.0.0; with the previous fallback 113 rows created more. Two features pin a factory bean of new cache managers beside a primary grailsCacheManager and beside one Spring cannot choose against. The count of what each arrangement created now counts every creation, where a list difference dropped the repeats of a cache manager created at startup. --- .../cache/GrailsCacheManagerFallback.groovy | 26 +++++++++- ...railsCacheManagerFallbackMatrixSpec.groovy | 47 +++++++++++++++++-- 2 files changed, 67 insertions(+), 6 deletions(-) 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 index 12556beba24..287e9e89c07 100644 --- a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy @@ -18,6 +18,8 @@ */ package org.grails.plugin.cache +import java.util.concurrent.ConcurrentHashMap + import groovy.transform.CompileStatic import org.springframework.beans.BeansException @@ -48,8 +50,9 @@ import org.springframework.core.ResolvableType * managers it cannot choose between, it takes {@code grailsCacheManager}. 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. The bean is registered as depending on the cache - * managers the resolution took, as the injection registers it. Any other injection of a cache manager is - * left alone.

+ * managers the resolution took, as the injection registers it, and the cache manager taken is remembered + * for the next injection of that bean, as the injection remembers it, so that a prototype bean resolves + * the field once. Any other injection of a cache manager is left alone.

* * @since 8.0.1 */ @@ -88,6 +91,12 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { private DefaultListableBeanFactory beanFactory + /** + * The cache manager each bean's field was given, by bean name and injection point, where the + * injection would remember it: one bean, of the field's type. + */ + private final Map, String> remembered = new ConcurrentHashMap, String>() + CandidateResolver(AutowireCandidateResolver delegate) { this.delegate = delegate } @@ -106,6 +115,13 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { if (proxy != null || beanFactory == null || descriptor instanceof FallbackDescriptor || !isTraitField(descriptor)) { return proxy } + List injectionPoint = Arrays.asList(beanName, descriptor) + String rememberedName = remembered.get(injectionPoint) + if (rememberedName != null && beanFactory.containsBean(rememberedName) && + beanFactory.isTypeMatch(rememberedName, descriptor.dependencyType)) { + // as the injection resolves a field it has resolved before, by the name of the bean it took + return beanFactory.getBean(rememberedName, descriptor.dependencyType) + } FallbackDescriptor fallback = new FallbackDescriptor(descriptor, beanFactory) Set autowiredBeanNames = new LinkedHashSet() Object value = beanFactory.doResolveDependency(fallback, beanName, autowiredBeanNames, null) @@ -120,6 +136,12 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { } } } + if (value != null && autowiredBeanNames.size() == 1) { + String autowiredBeanName = autowiredBeanNames.iterator().next() + if (beanFactory.containsBean(autowiredBeanName) && beanFactory.isTypeMatch(autowiredBeanName, descriptor.dependencyType)) { + remembered.putIfAbsent(injectionPoint, autowiredBeanName) + } + } return value } diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy index ef7031606a0..48bf6cc4f54 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy @@ -57,8 +57,9 @@ import grails.plugin.cache.GrailsCacheKeyGenerator * difference: where Spring could not choose, which failed startup, the class gets * {@code grailsCacheManager}, unless another cache manager is preferred, as primary or by priority, where * Spring rejects the tie itself. Otherwise the choice, and every failure, is 8.0.0's: what the cache-aware - * bean and a cache-aware {@code grailsCacheManager} get, the beans the cache-aware bean is registered as - * depending on, and how many of each cache manager are created, other than {@code grailsCacheManager}.

+ * bean, three instances of a prototype cache-aware bean and a cache-aware {@code grailsCacheManager} get, + * the beans the cache-aware bean is registered as depending on, and how many of each cache manager are + * created, other than {@code grailsCacheManager}.

*/ class GrailsCacheManagerFallbackMatrixSpec extends Specification { @@ -101,12 +102,22 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { String overCreated = ((List) now.created).countBy { it }.find { String name, Integer count -> count > (wasCreated[name] ?: 0) + (name == NAMED ? 1 : 0) }?.key + // the prototypes as in 8.0.0, and where 8.0.0 failed before them, as the probe's own resolution + Map prototypesMayCreate = ((fallsBack ? now.created : was.createdByPrototypes) ?: []).countBy { it } + String overCreatedByPrototypes = ((List) (now.createdByPrototypes ?: [])).countBy { it } + .find { String name, Integer count -> count > (prototypesMayCreate[name] ?: 0) }?.key if (got != expected) { mismatches << "${row}: got ${got}, expected ${expected} (8.0.0: ${was.failed ? 'failed' : was.chosen})".toString() } else if (overCreated) { mismatches << "${row}: created ${now.created}, where 8.0.0 created ${was.created}".toString() } + else if (overCreatedByPrototypes) { + mismatches << "${row}: prototypes created ${now.createdByPrototypes}, where 8.0.0 created ${was.createdByPrototypes}".toString() + } + else if (!now.failed && now.prototypes != (fallsBack ? [NAMED] * 3 : was.prototypes)) { + mismatches << "${row}: prototypes got ${now.prototypes}, where in 8.0.0 they got ${was.prototypes}".toString() + } else if (!now.failed && !was.failed && now.self != was.self) { mismatches << "${row}: grailsCacheManager got ${now.self}, where in 8.0.0 it got ${was.self}".toString() } @@ -141,12 +152,33 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { Map was = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], false) Map now = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], true) - expect: 'it is asked once, with the fallback as without it, and grailsCacheManager is injected' + expect: 'it is asked once for the injection, with the fallback as without it, and grailsCacheManager is injected' ((List) was.created).count('factory') == 1 ((List) now.created).count('factory') == 1 now.chosen == NAMED && was.chosen == NAMED } + void 'prototype beans resolve their cache manager once, as in 8.0.0, so a factory bean of new cache managers is asked once'() { + given: 'such a factory created first, beside a grailsCacheManager marked primary, and three prototype cache-aware beans' + Map was = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], false) + Map now = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], true) + + expect: 'the factory is asked once for the first prototype, then the choice is reused' + was.prototypes == [NAMED] * 3 && now.prototypes == [NAMED] * 3 + ((List) now.createdByPrototypes).count('factory') == ((List) was.createdByPrototypes).count('factory') + ((List) now.createdByPrototypes).count('factory') == 1 + } + + void 'prototype beans given grailsCacheManager where Spring cannot choose keep it, and create nothing more'() { + given: 'a factory bean of new cache managers and grailsCacheManager, which Spring cannot choose between' + Map now = run([factory: 'prototypeFactoryBean', (NAMED): 'plain'], true) + + expect: 'the first prototype asks the factory once, and the rest reuse the choice' + now.chosen == NAMED + now.prototypes == [NAMED] * 3 + ((List) now.createdByPrototypes).count('factory') == 1 + } + void 'a cache manager injected anywhere else is left as Spring resolves it'() { given: 'two cache managers Spring cannot choose between, and a bean of the application\'s own that injects one' GenericApplicationContext context = context([(NAMED): 'plain', first: 'plain'], [:], [], true) { GenericApplicationContext it -> @@ -204,6 +236,10 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { result.self = nameOf(((GrailsCacheManagerAware) started.getBean(NAMED)).grailsCacheManager, instances) } result.dependencies = (started.beanFactory.getDependenciesForBean('probe') as List).sort() + int beforePrototypes = created.size() + result.prototypes = (1..3).collect { nameOf(((CacheAware) started.getBean('prototype')).grailsCacheManager, instances) } + result.createdByPrototypes = new ArrayList(created.subList(beforePrototypes, created.size())) + created.subList(beforePrototypes, created.size()).clear() } catch (BeansException ignored) { result.failed = true @@ -211,7 +247,8 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { finally { started?.close() } - result.created = created - atStartup + // what was created after startup, each creation counted, as a list difference would drop repeats + result.created = new ArrayList(created.subList(atStartup.size(), created.size())) result } @@ -270,6 +307,8 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { } as Supplier, lazy) } context.registerBean('probe', CacheAware, lazy) + context.registerBean('prototype', CacheAware, + { BeanDefinition definition -> definition.scope = BeanDefinition.SCOPE_PROTOTYPE } as BeanDefinitionCustomizer) beforeRefresh?.call(context) context.refresh() context From dc451a9b5f671b4efb50e2549f3d3e72585c4ae9 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 22:53:05 -0800 Subject: [PATCH 19/20] Forget a bean's remembered cache manager when it is registered again The resolver remembered the cache manager a bean's field took, by bean name and injection point, for as long as the bean factory lived. Spring's injection forgets its own record when a bean definition is registered again or removed: the bean factory resets the definition, and AutowiredAnnotationBeanPostProcessor drops the bean's injection metadata, so the bean's fields are resolved afresh. After a reload that registered the bean again beside a new cache manager marked primary, the bean still got the cache manager it had before. The resolver is now a MergedBeanDefinitionPostProcessor too, added to the bean factory with it, and forgets what a bean's fields took when that bean's definition is reset, as the injection does. A feature injects a prototype, adds a cache manager marked primary, and registers the prototype again, where Spring chooses grailsCacheManager and where the fallback does: the choice is kept until the prototype is registered again and then made afresh, as in 8.0.0. With the previous resolver both kept grailsCacheManager. --- .../cache/GrailsCacheManagerFallback.groovy | 22 +++++++-- ...railsCacheManagerFallbackMatrixSpec.groovy | 48 +++++++++++++++++++ 2 files changed, 67 insertions(+), 3 deletions(-) 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 index 287e9e89c07..36a1af1ad1f 100644 --- a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy @@ -31,6 +31,8 @@ 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.beans.factory.support.MergedBeanDefinitionPostProcessor +import org.springframework.beans.factory.support.RootBeanDefinition import org.springframework.cache.CacheManager import org.springframework.core.ResolvableType @@ -52,7 +54,8 @@ import org.springframework.core.ResolvableType * at that moment, leaving out the bean being injected. The bean is registered as depending on the cache * managers the resolution took, as the injection registers it, and the cache manager taken is remembered * for the next injection of that bean, as the injection remembers it, so that a prototype bean resolves - * the field once. Any other injection of a cache manager is left alone.

+ * the field once, until the bean's definition is registered again or removed, when the injection forgets + * it too. Any other injection of a cache manager is left alone.

* * @since 8.0.1 */ @@ -69,7 +72,10 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { if (beanFactory instanceof DefaultListableBeanFactory) { DefaultListableBeanFactory listable = (DefaultListableBeanFactory) beanFactory if (!(listable.autowireCandidateResolver instanceof CandidateResolver)) { - listable.autowireCandidateResolver = new CandidateResolver(listable.autowireCandidateResolver) + CandidateResolver resolver = new CandidateResolver(listable.autowireCandidateResolver) + listable.autowireCandidateResolver = resolver + // told when a bean definition is registered again or removed, as the injection is + listable.addBeanPostProcessor(resolver) } } } @@ -85,7 +91,7 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { * {@code grailsCacheManager}. */ @CompileStatic - static class CandidateResolver implements AutowireCandidateResolver, BeanFactoryAware { + static class CandidateResolver implements AutowireCandidateResolver, BeanFactoryAware, MergedBeanDefinitionPostProcessor { private final AutowireCandidateResolver delegate @@ -145,6 +151,16 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { return value } + @Override + void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { + } + + /** Forgets what the bean's fields were given, as the injection forgets its own record of them. */ + @Override + void resetBeanDefinition(String beanName) { + remembered.keySet().removeIf { List injectionPoint -> injectionPoint[0] == beanName } + } + @Override boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { delegate.isAutowireCandidate(bdHolder, descriptor) diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy index 48bf6cc4f54..29f6c481232 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy @@ -179,6 +179,54 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { ((List) now.createdByPrototypes).count('factory') == 1 } + void 'a prototype bean registered again resolves its cache manager afresh, as in 8.0.0, where #arrangement'() { + when: 'a prototype is injected, a cache manager marked primary is added, and the prototype is registered again' + List was = reloaded(row, false) + List now = reloaded(row, true) + + then: 'the choice is kept until the prototype is registered again, and then made afresh' + now == expected + + and: 'as in 8.0.0, which kept its choice the same way; where it could not choose, it kept nothing to keep' + was == (row.first == 'plain' ? ['failed', 'preferred', 'preferred'] : expected) + + where: + arrangement | row + 'Spring chooses grailsCacheManager' | [(NAMED): 'plain'] + 'it is grailsCacheManager by the fallback' | [(NAMED): 'plain', first: 'plain'] + expected = [NAMED, NAMED, 'preferred'] + } + + /** What a prototype gets: at first, after a primary cache manager is added, and after it is registered again. */ + private List reloaded(Map row, boolean withFallback) { + Map instances = [:] + GenericApplicationContext context = context(row, instances, [], withFallback) + Closure inject = { -> + try { + nameOf(((CacheAware) context.getBean('prototype')).grailsCacheManager, instances) + } + catch (BeansException ignored) { + 'failed' + } + } + try { + List got = [inject()] + context.registerBean('preferred', CacheManager, { -> + CacheManager instance = new ConcurrentMapCacheManager() + instances.preferred = instance + instance + } as Supplier, { BeanDefinition definition -> definition.primary = true } as BeanDefinitionCustomizer) + got << inject() + context.registerBean('prototype', CacheAware, + { BeanDefinition definition -> definition.scope = BeanDefinition.SCOPE_PROTOTYPE } as BeanDefinitionCustomizer) + got << inject() + return got + } + finally { + context.close() + } + } + void 'a cache manager injected anywhere else is left as Spring resolves it'() { given: 'two cache managers Spring cannot choose between, and a bean of the application\'s own that injects one' GenericApplicationContext context = context([(NAMED): 'plain', first: 'plain'], [:], [], true) { GenericApplicationContext it -> From 5637ca3abb5533915d44768599014a331a6efc04 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 20 Nov 2026 07:05:59 -0800 Subject: [PATCH 20/20] Remember the cache manager by the injection point Spring passes, as Spring does The resolver remembered the cache manager a field took by bean name and an equal injection point, and forgot it when the bean factory it was installed in reset the bean. A copy of the resolver installed in another bean factory was never told of resets, so a bean registered again there kept the cache manager it had. The memory also differed from Spring's elsewhere: a remembered cache manager that was removed kept its name where Spring stores the new choice; the remembered one was fetched with getBean outside Spring's resolution, without the current injection point a prototype factory method may take, and without resolving again where it failed; and the injection Spring AOT generates, which resolves the field every time, was given the remembered one. Spring's field injection remembers its choice in the injection point it passes again for the bean's next injection, and a reset discards that injection point; AOT-generated injection passes a new one each time. The resolver now remembers by the identity of that injection point, held weakly, so it remembers exactly as long as Spring does, in any bean factory and for any copy of the resolver, and needs no notice of resets. A remembered cache manager is resolved through Spring's resolution as a shortcut, and where that fails the field is resolved again and the new choice remembered. The fallback no longer takes a grailsCacheManager that is Spring's null bean, and dependents are registered only where Spring registers them, for a value or a required field. The matrix gains a grailsCacheManager that is a fallback bean, not a default candidate, of a class with a priority, and Spring's null bean, so 1,596 arrangements, and allows grailsCacheManager to be created once more than in 8.0.0 only where it falls back, then with exactly grailsCacheManager among the dependencies. New features cover a remembered cache manager removed and replaced, a prototype cache manager made for its injection point, and three resolutions as AOT-generated code makes them, each against 8.0.0; all failed with the previous resolver, as did 13 null-bean rows. --- .../cache/GrailsCacheManagerFallback.groovy | 140 +++++++++---- .../cache/CacheAutoConfigurationSpec.groovy | 2 +- ...railsCacheManagerFallbackMatrixSpec.groovy | 192 ++++++++++++++++-- 3 files changed, 285 insertions(+), 49 deletions(-) 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 index 36a1af1ad1f..eab8bdfe92d 100644 --- a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy @@ -18,6 +18,9 @@ */ 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 @@ -31,8 +34,6 @@ 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.beans.factory.support.MergedBeanDefinitionPostProcessor -import org.springframework.beans.factory.support.RootBeanDefinition import org.springframework.cache.CacheManager import org.springframework.core.ResolvableType @@ -49,13 +50,19 @@ import org.springframework.core.ResolvableType * 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}. 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. The bean is registered as depending on the cache - * managers the resolution took, as the injection registers it, and the cache manager taken is remembered - * for the next injection of that bean, as the injection remembers it, so that a prototype bean resolves - * the field once, until the bean's definition is registered again or removed, when the injection forgets - * it too. Any other injection of a cache manager is left alone.

+ * 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 */ @@ -72,10 +79,7 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { if (beanFactory instanceof DefaultListableBeanFactory) { DefaultListableBeanFactory listable = (DefaultListableBeanFactory) beanFactory if (!(listable.autowireCandidateResolver instanceof CandidateResolver)) { - CandidateResolver resolver = new CandidateResolver(listable.autowireCandidateResolver) - listable.autowireCandidateResolver = resolver - // told when a bean definition is registered again or removed, as the injection is - listable.addBeanPostProcessor(resolver) + listable.autowireCandidateResolver = new CandidateResolver(listable.autowireCandidateResolver) } } } @@ -91,17 +95,19 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { * {@code grailsCacheManager}. */ @CompileStatic - static class CandidateResolver implements AutowireCandidateResolver, BeanFactoryAware, MergedBeanDefinitionPostProcessor { + static class CandidateResolver implements AutowireCandidateResolver, BeanFactoryAware { private final AutowireCandidateResolver delegate private DefaultListableBeanFactory beanFactory /** - * The cache manager each bean's field was given, by bean name and injection point, where the - * injection would remember it: one bean, of the field's type. + * 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, String> remembered = new ConcurrentHashMap, String>() + private final Map remembered = new ConcurrentHashMap() + + private final ReferenceQueue forgotten = new ReferenceQueue() CandidateResolver(AutowireCandidateResolver delegate) { this.delegate = delegate @@ -118,15 +124,26 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { @Override Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, String beanName) { Object proxy = delegate.getLazyResolutionProxyIfNecessary(descriptor, beanName) - if (proxy != null || beanFactory == null || descriptor instanceof FallbackDescriptor || !isTraitField(descriptor)) { + if (proxy != null || beanFactory == null || descriptor instanceof FallbackDescriptor || + descriptor instanceof RememberedDescriptor || !isTraitField(descriptor)) { return proxy } - List injectionPoint = Arrays.asList(beanName, descriptor) + Object shortcut = descriptor.resolveShortcut(beanFactory) + if (shortcut != null) { + // as the first step of Spring's resolution, for an injection point resolved in advance + return shortcut + } + forgetCollected() + InjectionPointKey injectionPoint = new InjectionPointKey(descriptor, null) String rememberedName = remembered.get(injectionPoint) - if (rememberedName != null && beanFactory.containsBean(rememberedName) && - beanFactory.isTypeMatch(rememberedName, descriptor.dependencyType)) { - // as the injection resolves a field it has resolved before, by the name of the bean it took - return beanFactory.getBean(rememberedName, descriptor.dependencyType) + if (rememberedName != null) { + try { + return beanFactory.doResolveDependency(new RememberedDescriptor(descriptor, rememberedName), beanName, null, null) + } + catch (BeansException ignored) { + // as the injection, which resolves the field again where the bean it remembers fails + remembered.remove(injectionPoint, rememberedName) + } } FallbackDescriptor fallback = new FallbackDescriptor(descriptor, beanFactory) Set autowiredBeanNames = new LinkedHashSet() @@ -134,7 +151,7 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { if (fallback.fellBack) { autowiredBeanNames << CACHE_MANAGER_BEAN_NAME } - if (beanName != null) { + if (beanName != null && (value != null || descriptor.required)) { // as the injection registers the bean it injects, which this answer takes the place of for (String autowiredBeanName : autowiredBeanNames) { if (beanFactory.containsBean(autowiredBeanName)) { @@ -145,20 +162,18 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { if (value != null && autowiredBeanNames.size() == 1) { String autowiredBeanName = autowiredBeanNames.iterator().next() if (beanFactory.containsBean(autowiredBeanName) && beanFactory.isTypeMatch(autowiredBeanName, descriptor.dependencyType)) { - remembered.putIfAbsent(injectionPoint, autowiredBeanName) + remembered.put(new InjectionPointKey(descriptor, forgotten), autowiredBeanName) } } return value } - @Override - void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { - } - - /** Forgets what the bean's fields were given, as the injection forgets its own record of them. */ - @Override - void resetBeanDefinition(String beanName) { - remembered.keySet().removeIf { List injectionPoint -> injectionPoint[0] == beanName } + /** Drops what was remembered for injection points Spring no longer holds. */ + private void forgetCollected() { + Reference reference + while ((reference = forgotten.poll()) != null) { + remembered.remove(reference) + } } @Override @@ -197,6 +212,55 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { } } + /** + * The identity of an injection point Spring passed, held weakly, so that an injection point is + * remembered as long as Spring holds it, and one equal to it is not taken for it. + */ + @CompileStatic + private static final class InjectionPointKey extends WeakReference { + + private final int hash + + InjectionPointKey(DependencyDescriptor injectionPoint, ReferenceQueue queue) { + super(injectionPoint, queue) + this.hash = System.identityHashCode(injectionPoint) + } + + @Override + int hashCode() { + hash + } + + @Override + boolean equals(Object other) { + if (this.is(other)) { + return true + } + if (!(other instanceof InjectionPointKey)) { + return false + } + Object injectionPoint = get() + injectionPoint != null && injectionPoint.is(((InjectionPointKey) other).get()) + } + } + + /** The trait's field, resolved to the cache manager remembered for it, as Spring resolves a shortcut. */ + @CompileStatic + private static class RememberedDescriptor extends DependencyDescriptor { + + private final String beanName + + RememberedDescriptor(DependencyDescriptor original, String beanName) { + super(original) + this.beanName = beanName + } + + @Override + Object resolveShortcut(BeanFactory beanFactory) throws BeansException { + beanFactory.getBean(beanName, dependencyType) + } + } + /** The trait's field, falling back to {@code grailsCacheManager} where Spring cannot choose. */ @CompileStatic private static class FallbackDescriptor extends DependencyDescriptor { @@ -215,10 +279,16 @@ class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { if (!matchingBeans.containsKey(CACHE_MANAGER_BEAN_NAME)) { return super.resolveNotUnique(type, matchingBeans) } - fellBack = true Object candidate = matchingBeans.get(CACHE_MANAGER_BEAN_NAME) // created here if it is not yet, as Spring creates the candidate it chooses - candidate instanceof Class ? resolveCandidate(CACHE_MANAGER_BEAN_NAME, CacheManager, beanFactory) : candidate + Object grailsCacheManager = candidate instanceof Class ? + resolveCandidate(CACHE_MANAGER_BEAN_NAME, CacheManager, beanFactory) : candidate + // Spring's null bean, which equals null: no cache manager to fall back to + if (grailsCacheManager == null || grailsCacheManager.equals(null)) { + return super.resolveNotUnique(type, matchingBeans) + } + fellBack = true + grailsCacheManager } } } diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 6a41540f1e4..cfd08c85f95 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -160,7 +160,7 @@ class CacheAutoConfigurationSpec extends Specification { GrailsCacheManager mine = Mock(GrailsCacheManager) AnnotationConfigApplicationContext context = buildContext([:], mine, [cacheManager: new ConcurrentMapCacheManager()]) - expect: 'it gets the alias too, so the context starts and caches with it' + expect: 'where Spring cannot choose, the cache-aware beans get it, so the context starts and caches with it' context.getBean(CacheAware).grailsCacheManager.is(mine) context.getBean(GrailsCacheAdminService).grailsCacheManager.is(mine) diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy index 29f6c481232..84641f659a7 100644 --- a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy @@ -24,17 +24,27 @@ import jakarta.annotation.Priority import org.springframework.beans.BeansException import org.springframework.beans.factory.FactoryBean +import org.springframework.beans.factory.InjectionPoint import org.springframework.beans.factory.NoUniqueBeanDefinitionException import org.springframework.beans.factory.UnsatisfiedDependencyException import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor +import org.springframework.beans.factory.aot.AutowiredFieldValueResolver import org.springframework.beans.factory.config.BeanDefinition import org.springframework.beans.factory.config.BeanDefinitionCustomizer import org.springframework.beans.factory.config.DependencyDescriptor import org.springframework.beans.factory.support.AbstractBeanDefinition import org.springframework.beans.factory.support.AutowireCandidateResolver +import org.springframework.beans.factory.support.DefaultListableBeanFactory +import org.springframework.beans.factory.support.RegisteredBean +import org.springframework.beans.factory.support.RootBeanDefinition import org.springframework.cache.CacheManager import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.AnnotationConfigUtils +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Scope import org.springframework.context.support.GenericApplicationContext import spock.lang.Specification @@ -66,7 +76,7 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { private static final String NAMED = GrailsCacheManagerFallback.CACHE_MANAGER_BEAN_NAME private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType', 'cyclic', - 'cacheAware'] + 'cacheAware', 'fallback', 'notDefault', 'priority', 'nullBean'] private static final List OTHER_KINDS = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', 'priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator', 'prototypeFactoryBean'] @@ -92,7 +102,7 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { rows.each { Map row -> Map was = run(row, false) Map now = run(row, true) - boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy', 'cacheAware'] + boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy', 'cacheAware', 'fallback', 'priority'] boolean anotherPreferred = row.any { String name, String kind -> name != NAMED && kind in PREFERRED_KINDS } // a context that does not start has failed before the cache-aware bean, where it cannot fall back boolean fallsBack = was.failed && !was.failedAtStartup && namedUsable && !anotherPreferred @@ -100,7 +110,7 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { Object got = now.failed ? 'failed' : now.chosen Map wasCreated = ((List) was.created).countBy { it } String overCreated = ((List) now.created).countBy { it }.find { String name, Integer count -> - count > (wasCreated[name] ?: 0) + (name == NAMED ? 1 : 0) + count > (wasCreated[name] ?: 0) + (fallsBack && name == NAMED ? 1 : 0) }?.key // the prototypes as in 8.0.0, and where 8.0.0 failed before them, as the probe's own resolution Map prototypesMayCreate = ((fallsBack ? now.created : was.createdByPrototypes) ?: []).countBy { it } @@ -121,7 +131,8 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { else if (!now.failed && !was.failed && now.self != was.self) { mismatches << "${row}: grailsCacheManager got ${now.self}, where in 8.0.0 it got ${was.self}".toString() } - else if (!now.failed && (fallsBack ? !(NAMED in (List) now.dependencies) : now.dependencies != was.dependencies)) { + else if (!now.failed && (fallsBack ? ((List) now.dependencies - ['customCacheKeyGenerator']) != [NAMED] : + now.dependencies != was.dependencies)) { mismatches << "${row}: depends on ${now.dependencies}, where 8.0.0 depended on ${was.dependencies}".toString() } } @@ -179,10 +190,10 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { ((List) now.createdByPrototypes).count('factory') == 1 } - void 'a prototype bean registered again resolves its cache manager afresh, as in 8.0.0, where #arrangement'() { + void 'a prototype bean registered again resolves its cache manager afresh, as in 8.0.0, where #arrangement#where'() { when: 'a prototype is injected, a cache manager marked primary is added, and the prototype is registered again' - List was = reloaded(row, false) - List now = reloaded(row, true) + List was = copied ? reloadedWithCopiedResolver(row, false) : reloaded(row, false) + List now = copied ? reloadedWithCopiedResolver(row, true) : reloaded(row, true) then: 'the choice is kept until the prototype is registered again, and then made afresh' now == expected @@ -191,10 +202,64 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { was == (row.first == 'plain' ? ['failed', 'preferred', 'preferred'] : expected) where: - arrangement | row - 'Spring chooses grailsCacheManager' | [(NAMED): 'plain'] - 'it is grailsCacheManager by the fallback' | [(NAMED): 'plain', first: 'plain'] + arrangement | row | copied + 'Spring chooses grailsCacheManager' | [(NAMED): 'plain'] | false + 'it is grailsCacheManager by the fallback' | [(NAMED): 'plain', first: 'plain'] | false + 'Spring chooses grailsCacheManager' | [(NAMED): 'plain'] | true + 'it is grailsCacheManager by the fallback' | [(NAMED): 'plain', first: 'plain'] | true expected = [NAMED, NAMED, 'preferred'] + where = copied ? ', in another bean factory with a copy of the resolver' : '' + } + + /** + * As {@link #reloaded}, in a bean factory of its own, with its own injection and a copy of the context's + * resolver, as {@code cloneIfNecessary} makes one for another bean factory. + */ + private List reloadedWithCopiedResolver(Map row, boolean withFallback) { + Map instances = [:] + GenericApplicationContext context = context([:], instances, [], withFallback) + DefaultListableBeanFactory factory = new DefaultListableBeanFactory() + factory.autowireCandidateResolver = context.defaultListableBeanFactory.autowireCandidateResolver.cloneIfNecessary() + AutowiredAnnotationBeanPostProcessor injection = new AutowiredAnnotationBeanPostProcessor() + injection.beanFactory = factory + factory.addBeanPostProcessor(injection) + Closure cacheManager = { String name, boolean primary -> + RootBeanDefinition definition = new RootBeanDefinition(CacheManager, { -> + CacheManager instance = new ConcurrentMapCacheManager() + instances[name] = instance + instance + } as Supplier) + definition.primary = primary + definition + } + Closure prototype = { -> + RootBeanDefinition definition = new RootBeanDefinition(CacheAware) + definition.scope = BeanDefinition.SCOPE_PROTOTYPE + definition + } + row.keySet().each { String name -> factory.registerBeanDefinition(name, cacheManager(name, false)) } + factory.registerBeanDefinition('prototype', prototype()) + Closure inject = { -> + try { + nameOf(((CacheAware) factory.getBean('prototype')).grailsCacheManager, instances) + } + catch (BeansException ignored) { + 'failed' + } + } + try { + assert (factory.autowireCandidateResolver instanceof GrailsCacheManagerFallback.CandidateResolver) == withFallback + List got = [inject()] + factory.registerBeanDefinition('preferred', cacheManager('preferred', true)) + got << inject() + factory.registerBeanDefinition('prototype', prototype()) + got << inject() + return got + } + finally { + factory.destroySingletons() + context.close() + } } /** What a prototype gets: at first, after a primary cache manager is added, and after it is registered again. */ @@ -227,6 +292,92 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { } } + void 'a remembered cache manager that is removed and replaced is replaced in the memory too, as in 8.0.0'() { + when: 'a prototype gets the only cache manager, which is removed for another, and then a primary one is added' + List was = replaced(false) + List now = replaced(true) + + then: 'the replacement is remembered in its place, and kept when the primary one is added' + was == ['first', 'second', 'second'] + now == was + } + + /** What a prototype gets: from first, from second after first is removed, and after a primary one is added. */ + private List replaced(boolean withFallback) { + Map instances = [:] + GenericApplicationContext context = context([first: 'plain'], instances, [], withFallback) + Closure inject = { -> nameOf(((CacheAware) context.getBean('prototype')).grailsCacheManager, instances) } + Closure register = { String name, boolean primary -> + context.registerBean(name, CacheManager, { -> + CacheManager instance = new ConcurrentMapCacheManager() + instances[name] = instance + instance + } as Supplier, { BeanDefinition definition -> definition.primary = primary } as BeanDefinitionCustomizer) + null + } + try { + List got = [inject()] + context.removeBeanDefinition('first') + register('second', false) + got << inject() + register('third', true) + got << inject() + return got + } + finally { + context.close() + } + } + + void 'a remembered prototype cache manager made for its injection point gets one, as in 8.0.0'() { + given: 'a prototype cache manager whose factory method takes the injection point, and a prototype cache-aware bean' + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() + context.addBeanFactoryPostProcessor(new GrailsCacheManagerFallback()) + context.register(PerInjectionPoint) + context.registerBean('prototype', CacheAware, + { BeanDefinition definition -> definition.scope = BeanDefinition.SCOPE_PROTOTYPE } as BeanDefinitionCustomizer) + context.refresh() + + when: 'the prototype is injected again, from what is remembered' + List got = (1..3).collect { ((CacheAware) context.getBean('prototype')).grailsCacheManager } + + then: 'each injection made one, for the field' + got.every { it instanceof PerInjectionPointCacheManager && ((PerInjectionPointCacheManager) it).field?.name == GrailsCacheManagerFallback.FIELD_NAME } + got*.hashCode().unique().size() == 3 + + cleanup: + context?.close() + } + + void 'the injection Spring AOT generates resolves the field every time, as in 8.0.0'() { + given: 'a factory bean of new cache managers beside a primary grailsCacheManager, as in the prototype features' + Map was = aotResolved(false) + Map now = aotResolved(true) + + expect: 'each of three resolutions asks the factory, with the fallback as without it' + was.chosen == [NAMED] * 3 && now.chosen == [NAMED] * 3 + ((List) was.created).count('factory') == 3 + ((List) now.created).count('factory') == 3 + } + + /** Resolves the trait's field three times as AOT-generated code does, with a new injection point each time. */ + private Map aotResolved(boolean withFallback) { + Map instances = [:] + List created = [] + GenericApplicationContext context = context([factory: 'prototypeFactoryBean', (NAMED): 'primary'], instances, created, withFallback) + try { + int startup = created.size() + RegisteredBean prototype = RegisteredBean.of(context.defaultListableBeanFactory, 'prototype') + List chosen = (1..3).collect { + nameOf((CacheManager) AutowiredFieldValueResolver.forField(GrailsCacheManagerFallback.FIELD_NAME).resolve(prototype), instances) + } + return [chosen: chosen, created: new ArrayList(created.subList(startup, created.size()))] + } + finally { + context.close() + } + } + void 'a cache manager injected anywhere else is left as Spring resolves it'() { given: 'two cache managers Spring cannot choose between, and a bean of the application\'s own that injects one' GenericApplicationContext context = context([(NAMED): 'plain', first: 'plain'], [:], [], true) { GenericApplicationContext it -> @@ -245,11 +396,11 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { context?.close() } - void 'the resolver is installed once, and a copy of it falls back too'() { + void 'the resolver is installed once, and copied as itself'() { given: GenericApplicationContext context = context([(NAMED): 'plain'], [:], [], true) - when: 'post-processed again, as a parent and child context sharing it would be' + when: 'post-processed again' new GrailsCacheManagerFallback().postProcessBeanFactory(context.beanFactory) AutowireCandidateResolver resolver = context.defaultListableBeanFactory.autowireCandidateResolver @@ -324,7 +475,8 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { context.getBean('probe') } created << name - CacheManager instance = type.getDeclaredConstructor().newInstance() + // a factory method that returns null makes Spring's null bean + CacheManager instance = kind == 'nullBean' ? null : type.getDeclaredConstructor().newInstance() instances[name] = instance instance } as Supplier @@ -384,6 +536,20 @@ class GrailsCacheManagerFallbackMatrixSpec extends Specification { static class HighPriorityCacheManager extends ConcurrentMapCacheManager { } + /** A cache manager made for the injection point it is injected into. */ + static class PerInjectionPointCacheManager extends ConcurrentMapCacheManager { + java.lang.reflect.Field field + } + + @Configuration(proxyBeanMethods = false) + static class PerInjectionPoint { + @Bean + @Scope(BeanDefinition.SCOPE_PROTOTYPE) + static CacheManager perInjectionPoint(InjectionPoint injectionPoint) { + new PerInjectionPointCacheManager(field: injectionPoint.field) + } + } + /** A grailsCacheManager that is cache-aware itself, which Spring leaves out of the candidates for its own field. */ static class CacheAwareCacheManager extends ConcurrentMapCacheManager implements GrailsCacheManagerAware { }