Skip to content

8.0 (fix): Start with another CacheManager next to the Grails cache plugin's - #16980

Open
codeconsole wants to merge 25 commits into
apache:8.0.xfrom
codeconsole:fix/cache-users-cache-manager-8.0.x
Open

codeconsole wants to merge 25 commits into
apache:8.0.xfrom
codeconsole:fix/cache-users-cache-manager-8.0.x

Conversation

@codeconsole

@codeconsole codeconsole commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

An application with the cache plugin failed to start when the application context had a second CacheManager and neither was marked primary or had a @Priority. grails-dependencies-starter-web brings the cache plugin in, and the Spring Security plugin defines a CacheManager named cacheManager when cacheUsers is set:

Error creating bean with name 'grailsCacheAdminService': Unsatisfied dependency expressed through field
'org_grails_plugin_cache_GrailsCacheManagerAware__grailsCacheManager': No qualifying bean of type
'org.springframework.cache.CacheManager' available: expected single matching bean but found 2:
cacheManager,grailsCacheManager

GrailsCacheManagerAware, the trait every cache-aware class implements, injects a CacheManager by type. Where Spring cannot choose by type, it falls back to the bean named like the field. But a trait's field is renamed in the class that implements it, so no bean matched.

The fix

GrailsCacheManagerFallback, a bean factory post-processor of the plugin's auto-configuration, wraps the bean factory's autowire candidate resolver. Spring asks that resolver, right before it resolves a dependency and with the bean being injected, whether to inject a proxy instead. For the trait's field the resolver answers with the field's resolution itself, done once. It is Spring's own doResolveDependency for that bean, with a descriptor that changes one thing:

  • Where Spring can choose, it chooses as it did, at that moment: the only cache manager, the one marked primary, or the one with the highest priority. It judges the objects of the cache managers created by then, factory bean products included, and leaves out the bean being injected.
  • Only where Spring would fail because it cannot choose, and grailsCacheManager is one of the cache managers it cannot choose between, is the field given grailsCacheManager, unless its factory method returned null.
  • The bean is registered as depending on the cache managers the resolution took, as the injection registers it, so it stops and is destroyed before them.
  • The cache manager taken is remembered for the injection point Spring resolved, held weakly. Spring's field injection passes that injection point again for a prototype's next instance, and discards it when the bean is registered again or removed; AOT-generated injection passes a new one each time. So the field is reused and resolved again exactly as Spring would, in any bean factory. A remembered cache manager that fails is resolved again.
Beside grailsCacheManager 8.0.0 Now
another cache manager, as with cacheUsers startup fails grailsCacheManager
one marked primary the primary one the primary one
one with a @Priority, on its class or only on its object that one that one
  • The trait is unchanged, so classes compiled against 8.0.0, in plugins too, get the fix without being recompiled.
  • Any other injection of a cache manager, such as a field of the application's own, is left as Spring resolves it.
  • A grailsCacheManager that a cache provider plugin or the application defines is used as well. With grails.cache.enabled: false the plugin defines none, and nothing changes unless the application defines one.
  • A lazy cache manager is not created, and two cache managers marked primary, or two with the same highest priority, still fail, as Spring rejects them itself.

A cache the cache manager does not have

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. The code the cache annotations generate used that null, so every call failed with a NullPointerException. Now a @Cacheable or @CachePut method runs uncached, @CacheEvict has nothing to evict, and MissingCacheReporter warns once for each cache manager and name, naming the class. Classes compiled against this version get this fix.

Tests

  • GrailsCacheManagerFallbackMatrixSpec checks 1,596 arrangements against 8.0.0 itself: the same class in the same context, without the fallback.
    • grailsCacheManager: absent, plain, primary, lazy, not an autowire candidate, a fallback bean, not a default candidate, with a @Priority, of the wrong type, Spring's null bean, created from the cache-aware bean, or cache-aware itself.
    • The other cache managers: none, one or two of them, each plain, primary, lazy, not an autowire candidate, fallback, not a default candidate, or with a @Priority. The priority is on the class, only on the object a bean declared as CacheManager returns, on the product of a factory bean that names only CacheManager, or on a cache manager the cache-aware bean's key generator creates while that bean is injected. One is a factory bean that makes a new cache manager each time it is asked.
    • Each row checks against 8.0.0 which cache manager the cache-aware bean gets, what three instances of a prototype cache-aware bean get and create, what a cache-aware grailsCacheManager gets, the beans the cache-aware bean is registered as depending on, and how many times each cache manager is created. The only difference allowed: where 8.0.0 failed and no other cache manager is preferred, the class gets grailsCacheManager, and depends on it.
    • A prototype registered again after a cache manager marked primary is added resolves its field afresh, as in 8.0.0, also in another bean factory with a copy of the resolver. So does one whose remembered cache manager is removed and replaced, one whose prototype cache manager takes its InjectionPoint, and the injection that Spring AOT generates.
    • The spec also checks cache managers registered as singletons without a bean definition, that a cache manager injected into a field of the application's own still fails where Spring cannot choose, that the fallback targets the trait field's real compiled name, and that the resolver is installed once.
  • MissingCacheSpec creates annotated classes as beans, compiled statically and dynamically, beside a second cache manager. It covers default keys and a key closure, and each annotation with a missing cache.
  • CacheAutoConfigurationSpec covers the plugin's auto-configuration:
    • another cache manager beside the plugin's grailsCacheManager, and beside one the application defines;
    • a primary cache manager;
    • a lazy cache manager whose creation fails;
    • an application grailsCacheManager created from a cache-aware bean, beside a cache manager that is primary, has a @Priority, has one only on the object its factory returns, is the product of a factory bean, or is created by the key generator;
    • a grailsCacheManager that is cache-aware itself, with circular references allowed and disallowed;
    • the stop order of a cache-aware bean given grailsCacheManager through the fallback.
  • All grails-cache tests pass, as do the grails-test-examples/cache app's tests and the CachingSpec of grails-test-examples/app1 and hibernate7/app1.

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.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not approving. With caching auto-configuration off and several cache managers, one marked primary, the plugin's manager is no longer chosen. Caching is skipped.

… one

621a2a8 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.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not approving. The case with no named plugin manager and a primary manager is fixed. When the named plugin manager is present, a different primary manager is chosen instead.

210ee4d 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.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not approving. The named plugin manager is now chosen before a primary one, and a primary one is still used when the name is absent. Injecting every cache manager starts a lazy manager that used to stay uncreated, so startup can fail.

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.
…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.
…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<CacheManager>, 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.
…rity 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.
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.
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.
jamesfredley
jamesfredley previously approved these changes Nov 14, 2026

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The named plugin manager is chosen when it is present. A primary manager is used when that name is absent. A lazy manager is not created just to look the others up.

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.
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.
jamesfredley
jamesfredley previously approved these changes Nov 14, 2026

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A cached method runs uncached when its cache does not exist, and still uses the cache when it does. The named manager, the primary fallback, and the lazy manager are unchanged.

matrei
matrei previously requested changes Nov 17, 2026

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of #16980 at 134856bdf08 (base 8.0.x). It is 11 commits on 88272db2f39. 8.0.x has moved 4 commits since then, and the PR merges into its tip, ab241626398, without conflicts.

What I ran, on Java 21:

  • The grails-cache suite, rerun without the build cache: 53 tests, no failures. That includes the 14 features of GrailsCacheManagerLookupMatrixSpec, both of MissingCacheSpec and the 17 of CacheAutoConfigurationSpec.
  • The grails-test-examples/cache app: test (19) and integrationTest (25), no failures.
  • A probe spec of my own (not pushed), with a class that gets the trait from @Cacheable rather than from implements, compiled statically and dynamically. Created as a bean beside a second cache manager named cacheManager, it gets grailsCacheManager through the new injectGrailsCacheManager. Methods with a key closure or a condition closure run uncached where the cache is missing, and a key closure on a configured cache still caches.
  • The alternative in 1, against a class compiled with the PR's 8.0.0 trait fixture. The results are in 1.

@codeconsole, thanks, and thanks for building the matrix against the old injection. The cacheUsers failure is real and should be fixed on 8.0.x. My main concern is that the fix also changes which cache manager an application that starts today uses, and a patch release can't do that.

1. Applications that start on 8.0.0 move to another cache manager

GrailsCacheManagerLookup.groovy:101 takes the bean named grailsCacheManager before Spring's own choice. Take an application with a cache manager of its own, marked primary or with a @Priority, next to grailsCacheManager. With 8.0.0 it starts, and its Grails cache annotations and GrailsCacheAdminService use that cache manager. The trait's field is the same on 7.0.x, so this has been the behaviour for a long time. With this PR they use grailsCacheManager instead, and the only sign is an INFO line (upgrading80x.adoc:4986, CacheAutoConfigurationSpec.groovy:203).

For example, take an application whose nodes share a primary Redis cache manager. After a patch upgrade, its annotations would cache in the in-memory GrailsConcurrentMapCacheManager. Each node then caches on its own, and a @CacheEvict on one node no longer evicts what the other nodes serve. RELEASE.md describes a patch release as "backward-compatible bug fixes. If incremented, should involve no work", and the PR template limits patch branches to bug fixes. Section 94, however, asks these applications to redefine their cache manager as grailsCacheManager.

The startup failure only needs a fix where Spring cannot choose. I know @jamesfredley asked for the name first in round 2, and I agree it's the better rule, but it belongs in 9.0.x with an upgrade note. On 8.0.x I'd keep Spring's choice wherever Spring made one.

A much smaller fix does exactly that. When Spring cannot choose, it falls back to matching the dependency's name, aliases included. That step comes after primary and before @Priority (see DefaultListableBeanFactory.determineAutowireCandidate, and the name shortcut in doResolveDependency). In every class that implements the trait, its field is named org_grails_plugin_cache_GrailsCacheManagerAware__grailsCacheManager. So if the plugin registers that name as an alias of grailsCacheManager, the injection from 8.0.0 picks grailsCacheManager where it used to be ambiguous, and nothing else changes. I checked it with a class compiled against the 8.0.0 trait, beside a plain grailsCacheManager, varying the other cache manager:

Other cache manager Without the alias (8.0.0) With the alias
plain, as with cacheUsers fails, two candidates grailsCacheManager
primary not run the primary one, as in 8.0.0
lazy not run grailsCacheManager, and the lazy one is not created
fallback not run grailsCacheManager
@Priority the @Priority one grailsCacheManager

The alias is better than the trait method in several ways:

  • It also fixes classes compiled against 8.0.0. Section 94 (:4988) says those still fail beside a second cache manager with this PR.
  • The trait stays as it is. That means no injectGrailsCacheManager, no 8.0.1 runtime requirement for plugins (:4990), no INFO report, and no lookup to check against Spring, because Spring keeps resolving.
  • With caching turned off there is no alias, so the behaviour stays as in 8.0.0. That includes failing where Spring cannot choose, and I'm fine leaving that alone on a patch line.
  • It changes one case: a @Priority cache manager (not primary) next to grailsCacheManager, because the name now comes before the priority. That's rare, but it should get a line in the upgrade notes.

If you'd rather keep the current design, find could call cacheManagers.getObject() first, and look up grailsCacheManager by name only on NoUniqueBeanDefinitionException. That keeps 8.0.0's choice, the @Priority case included. But classes compiled against 8.0.0 still fail, and the 8.0.1 runtime requirement stays. I'd go with the alias, and move the name-first rule to a PR against 9.0.x.

The null check for a missing cache fixes an NPE, so it fits 8.0.x either way. With the alias, the only reference to something new at runtime would be the reportMissingCache call, and that runs only where a cache is missing.

2. MissingCacheSpec sets the trait's field by its compiled name

MissingCacheSpec.groovy:43 writes the field org_grails_plugin_cache_GrailsCacheManagerAware__grailsCacheManager directly. That is Groovy's internal name for the trait's private field, so the spec skips the way a class gets its cache manager. It also leaves a gap. No spec in grails-cache creates a class that gets the trait from a cache annotation as a bean. So nothing in the module checks that the transformation's classes get injectGrailsCacheManager and that Spring calls it. Only the cache example app does.

Creating the compiled class as a bean covers both. I ran this for both modes and it passes:

GenericApplicationContext context = new GenericApplicationContext()
AnnotationConfigUtils.registerAnnotationConfigProcessors(context)
context.registerBean('grailsCacheManager', CacheManager, { -> cacheManager } as Supplier<CacheManager>)
context.registerBean('service', (Class<Object>) compile(mode))
context.refresh()
def service = context.getBean('service')

With the alias from 1 this holds too: the bean then gets its cache manager through the field. A @Cacheable method with a key closure would be worth adding, as the key generation is part of what moved into the new if.

3. Small things

  • GrailsCacheManagerLookupMatrixSpec.groovy:98, the matrix covers the arrangements it says it does, checks the spec's own row generator rather than any Grails code. If the matrix stays, an assert in the matrix feature is enough.
  • upgrading80x.adoc:4976: #16935 and #16836 also add a section 94, so whichever merges second needs to renumber.
  • On 7.0.x, the trait's field and the cacheManager bean that cacheUsers defines are the same, so I expect the same startup failure there. With the alias, the fix is small enough to land on 7.0.x and merge up. Do you plan a 7.0.x PR?

Verified as correct

  • The 8.0.0 trait fixture is identical to the trait on 8.0.x before this PR (I diffed them). The compatibility feature loads only the compiled class beside the new trait, and it passes.
  • Classes the transformation weaves get the trait's @Autowired method (probe above).
  • Moving the parameter map and key generation into the if (cache != null) block works. key and condition closures still compile and run in both modes (probe), and so does @CacheEvict(allEntries = true) (MissingCacheSpec).
  • find creates only the cache manager it returns (the lazy rows of the matrix, and CacheAutoConfigurationSpec). Taking the bean factory through a provider covers a bare DefaultListableBeanFactory.
  • cacheManager.adoc and section 94 describe the code as it stands. The note that a replacement grailsCacheManager has to implement GrailsCacheManager matches CacheGrailsPlugin.doWithApplicationContext, which looks the bean up with that type.


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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When updating the ugprade guide, we must upgrade the skill too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in d5fd4e8: the cache case is now also in the Grails 8 upgrade skill (grails-skills/upgrade-guide-8/skills/grails-8-upgrade/SKILL.md, "Cache Plugin Beside Another Cache Manager"), matching section 94.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update after merging 8.0.x in 918c5dd: grails-8-upgrade is now a pointer to grails-upgrade, so the cache entry moved to grails-skills/upgrade/skills/grails-upgrade/SKILL.md, under "Grails 8.0.1" as "Cache Plugin Beside Another Cache Manager". It matches the guide section, which is now unnumbered under Grails 8.0.1 like the rest of that release's changes.

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.
@codeconsole

Copy link
Copy Markdown
Contributor Author

@matrei thanks, I went with the alias. It's in d5fd4e8.

1. Which cache manager is used. The trait is 8.0.0's again, unchanged. GrailsCacheManagerAliasRegistrar, a bean factory post-processor of the plugin's auto-configuration, gives grailsCacheManager the trait field's compiled name as an alias. It runs after every definition is in, so a grailsCacheManager that a provider plugin or the application defines gets it too. With caching off there's no alias, so nothing changes there. The injection method, the 8.0.1 runtime requirement, the INFO report and the lookup are all gone.

GrailsCacheManagerAliasMatrixSpec now uses 8.0.0 itself as its oracle: the same class, in the same context, without the alias. Across the 342 arrangements, the only differences are these:

  • where 8.0.0 couldn't choose, grailsCacheManager is used;
  • a @Priority cache manager beside grailsCacheManager now loses to it, which section 94 notes.

One thing it showed that your table didn't cover: two cache managers marked primary still fail with the alias, because Spring rejects them before it looks at names. That's as in 8.0.0, and the spec expects it. Your table holds in every other row. A primary cache manager is used as in 8.0.0, and CacheAutoConfigurationSpec asserts that again.

The missing-cache fix stays, with the report moved to MissingCacheReporter.

2. MissingCacheSpec. The annotated class is now created as a bean, compiled statically and dynamically, beside a second cache manager, so it gets grailsCacheManager through its field with the alias. A @Cacheable with a key closure is covered for both a missing and a configured cache.

3. Small things.

@jamesfredley, this moves away from the name-first rule you asked for in round 2. A patch release can't change which cache manager an application that starts today uses. On 8.0.x, Spring's choice now stands wherever Spring made one, and grailsCacheManager is taken only where it couldn't choose, which is the cacheUsers case. The name-first rule can go into a 9.0.x PR with an upgrade note.

All grails-cache tests pass, as do the grails-test-examples/cache app's tests and the CachingSpec of app1 and hibernate7/app1.

…rity

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.
sbglasius
sbglasius previously approved these changes Nov 19, 2026

@sbglasius sbglasius left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an AI assisted review

Reviewed at 4d4da50f11. The alias approach is much better than the earlier trait rewrites. The trait stays as it was in 8.0.0, Spring still makes the choice, and the only new thing is the alias. It relies on Spring 6.2+ resolving a dependency by name first (canonicalName follows aliases, and hasPrimaryConflict keeps primary beans ahead). Leaving the alias out when another cache manager has a @Priority fixes the self-reference case James found. Testing the matrix against 8.0.0's own behavior makes a solid test.

A few small points, none blocking:

  1. @Priority behind a factory method. preferredBySpring reads the priority from getType(name, false). A @Bean CacheManager foo() whose returned object has @Priority on its class therefore isn't seen. In 8.0.0, Spring read the priority from the created instance and picked that bean. With the alias, it now picks grailsCacheManager. This is a narrow change in behavior, and the PR description mentions it, but the user docs and the upgrade notes say "or the one with the highest @Priority" without that caveat. Please add half a sentence there, or have the matrix pin this case as a known difference.

  2. Missing cache runs uncached instead of failing. This differs from Spring's own CacheAspectSupport, which throws Cannot find cache named '…'. A WARN that fires once can easily be missed in production, and a misconfigured cache name then quietly turns into "no caching". I'm fine with this, given that the alternative was an NPE on every call, but was failing fast at the first call considered? The change is also separate from the startup fix and could have been its own PR. Just noting that, not asking for a split now.

CI is still running at the time of this review.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. A manager marked to be chosen first still stops startup when that mark is on the class the factory returns, not on the declared type.

return true
}
}
Class<?> type = beanFactory.getType(name, false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second manager is a bean whose declared type is CacheManager and whose returned class is marked to be chosen first. This registrar sees only the declared type, so it still adds the alias. Creating the application's manager then asks for itself and startup fails. Look at the class the factory returns before adding the alias.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this holds, with one condition. Spring reads a candidate's priority from its object only once that bean exists; before that it reads the type the factory method declares. So where the @Priority cache manager was created before the application's grailsCacheManager, 8.0.0 injected it and started, and the alias made the cache-aware bean ask for grailsCacheManager while it was being created. Where it's created after, 8.0.0 failed too, with two candidates.

The registrar can't look at the returned class itself: it runs before those beans exist, and creating them there would create a lazy cache manager early and skip the bean post-processors. So in eebd2bb the check also runs where Spring chooses. With the alias, the registrar adds a bean post-processor that runs the check again before the first cache-aware bean is injected. By then the cache managers already created report the class of their object, as Spring sees them in that injection, and the alias is removed where one of them has a priority. It creates no bean, and it decides once, so every cache-aware bean gets the same cache manager.

  • CacheAutoConfigurationSpec has your case: a @Priority cache manager declared as CacheManager and created first. It fails at 4d4da50 and passes now.
  • The matrix has a cache manager of that kind too, so 511 arrangements. At 4d4da50, 24 of them got grailsCacheManager where 8.0.0 got the @Priority one; now all match 8.0.0.

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.
@codeconsole

Copy link
Copy Markdown
Contributor Author

@sbglasius thanks.

  1. Right, with one condition: 8.0.0 read the priority from the object only where that bean was created before the injection. Otherwise it read CacheManager from the factory method and failed with two candidates. James found the same case in his latest thread. In eebd2bb, a bean post-processor runs the registrar's check again before the first cache-aware bean is injected. Where another cache manager created by then has a @Priority on its object, it removes the alias, so Spring chooses as in 8.0.0 there. The matrix now pins the case, a cache manager declared as CacheManager whose object has a @Priority, and those rows match 8.0.0. So "the one with the highest @Priority" in the docs holds as it does for Spring itself, and needs no caveat.
  2. Failing fast wasn't weighed as such. Uncached is what the generated code already does with no cache manager. And the case that found the NPE is caching turned off with cacheUsers set: the annotations then get Spring Security's JCacheCacheManager, which has none of the application's caches. Failing on the first call would still break every cached method in an application that turned caching off. The warning names the class, the cache and the cache manager.

@github-actions
github-actions Bot dismissed sbglasius’s stale review November 19, 2026 19:06

Dismissed automatically: the pull request changed after this approval, from 4d4da50 to eebd2bb.

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed again at f88b3ea0869. The upgrade-skill update is present and matches the guide. The unchanged trait and alias address the original ambiguous injection, but two reproducible cases still change Spring's previous choice and can prevent startup. I would address these before merging.

I checked the registrar from this exact head in real Spring application contexts, with the published Grails 8.0.0 trait, on Java 21, Groovy 5.1.3 and Spring 7.0.10. For each case I ran the same context with and without the registrar:

Arrangement Without registrar With this PR's registrar
Custom key generator creates the priority manager during injection Priority manager grailsCacheManager
Same, with grailsCacheManager created from the cache-aware bean Starts; priority manager BeanCurrentlyInCreationException
An initialized FactoryBean<CacheManager> reports CacheManager as its object type and returns a priority manager Priority manager grailsCacheManager
Same factory, with grailsCacheManager created from the cache-aware bean Starts; priority manager BeanCurrentlyInCreationException

The inline comments describe the two causes and the missing regression coverage. The existing matrix does not cover a key-generator dependency or a FactoryBean product.

Verification limit: I attempted :grails-cache:test on Java 21, including offline, but the full build repeatedly exceeded the command timeout during configuration before reaching the tests. I am not claiming a local suite pass. The current main CI builds passed; the red Groovy snapshot canary reports five Db2 container-image pull timeouts.

Comment on lines +154 to +156
PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
if (bean instanceof GrailsCacheManagerAware && checked.compareAndSet(false, true) &&
anotherPreferred(beanFactory, true)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Check the priority at cache-manager resolution, after earlier dependencies have been injected. This callback runs before AutowiredAnnotationBeanPostProcessor, so its view of the instantiated managers can already be stale when Spring reaches the trait's cache-manager field. The trait injects customCacheKeyGenerator first. I reproduced this with a custom key-generator supplier that depends on preferredCacheManager, declared as CacheManager but returning an @Priority(1) implementation. The callback sees only CacheManager and permanently keeps the alias; injecting the key generator then creates the preferred manager, but the following cache-manager injection takes grailsCacheManager through the alias. Without the registrar, Spring sees the newly created object's priority and chooses it. If grailsCacheManager itself is constructed from this cache-aware bean, the same configuration starts without the registrar and fails here with BeanCurrentlyInCreationException. Please cover this dependency ordering and preserve Spring's decision at the actual injection point; a once-only check before property injection does not do that.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed: a key generator that creates the @Priority cache manager while the cache-aware bean is injected made the alias win where 8.0.0 took the @Priority one. With grailsCacheManager created from that bean, startup failed.

You're right that a check before property injection can't hold Spring's decision, and neither could any earlier check. So 1047ebb drops the alias and the checks. GrailsCacheManagerFallback wraps the bean factory's autowire candidate resolver instead. When Spring resolves the trait's field, after the key generator has been injected, the resolver first runs Spring's own resolution of that field, with a descriptor that:

  • creates no cache manager that Spring wouldn't create to compare them: the existing ones and the products of existing factory beans;
  • notes where Spring can't choose.

Where Spring can choose, the resolver steps aside, and Spring resolves the field at that moment as in 8.0.0. Only where Spring would fail because it can't choose, and grailsCacheManager is one of the candidates, does the field get grailsCacheManager. Nothing else that injects a cache manager is touched.

Your case is in CacheAutoConfigurationSpec, with grailsCacheManager created from the cache-aware bean, and in the matrix as a cache manager the key generator creates. Both fail with the alias registrar and pass now.

Comment on lines +117 to +118
Class<?> type = beanFactory.getType(name, allowFactoryBeanInit)
return type != null && OrderUtils.getPriority(type) != null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the priority of a FactoryBean product, not just its advertised type. For a FactoryBean<CacheManager>, getType(name, true) still uses getObjectType(), which may legitimately return CacheManager.class even when getObject() returns an @Priority(1) implementation. This differs from an ordinary singleton: when the factory is already initialized, Spring's findAutowireCandidates resolves its product and considers the product's priority. I reproduced this with the factory registered before the cache-aware bean: without the registrar the priority product is injected, while this head keeps the alias and injects grailsCacheManager. Making grailsCacheManager depend on the cache-aware bean turns that selection change into a startup BeanCurrentlyInCreationException; the same context starts without the registrar. Passing true or repeating this type check cannot recover the product's priority. Please add a real FactoryBean case to the regression tests and preserve Spring's product-based selection.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed too: a FactoryBean<CacheManager> advertising CacheManager and returning a @Priority product kept the alias.

Fixed in 1047ebb by the same change as your timing point: there's no alias or type check any more. Spring's own resolution decides, through findAutowireCandidates, and for an initialized factory that means the product and its priority. grailsCacheManager is used only where that resolution can't choose.

  • CacheAutoConfigurationSpec has a real FactoryBean registered before the cache-aware bean, with grailsCacheManager created from that bean. It failed to start with the alias registrar and starts now with the product injected.
  • The matrix has the same factory as a kind of cache manager. It now runs 777 arrangements against 8.0.0, and 67 of them differed with the alias registrar.

…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.
@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 74.78261% with 29 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.5387%. Comparing base (0518f48) to head (5637ca3).
⚠️ Report is 3 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
...ils/plugin/cache/GrailsCacheManagerFallback.groovy 67.9012% 8 Missing and 18 partials ⚠️
...rg/grails/plugin/cache/MissingCacheReporter.groovy 66.6667% 2 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16980        +/-   ##
==================================================
+ Coverage     62.4963%   62.5387%   +0.0424%     
- Complexity      27472      27491        +19     
==================================================
  Files            2249       2251         +2     
  Lines          111693     111798       +105     
  Branches        20478      20501        +23     
==================================================
+ Hits            69804      69917       +113     
+ Misses          32537      32502        -35     
- Partials         9352       9379        +27     
Files with missing lines Coverage Δ
.../cache/compiler/AbstractCacheTransformation.groovy 93.8053% <100.0000%> (+0.6681%) ⬆️
...gin/cache/compiler/CacheEvictTransformation.groovy 95.6522% <100.0000%> (+0.1976%) ⬆️
...lugin/cache/compiler/CachePutTransformation.groovy 94.4444% <100.0000%> (+94.4444%) ⬆️
...ugin/cache/compiler/CacheableTransformation.groovy 85.7143% <100.0000%> (+0.5291%) ⬆️
...roovy/grails/plugin/cache/CacheGrailsPlugin.groovy 68.1818% <100.0000%> (+1.5152%) ⬆️
...rg/grails/plugin/cache/MissingCacheReporter.groovy 66.6667% <66.6667%> (ø)
...ils/plugin/cache/GrailsCacheManagerFallback.groovy 67.9012% <67.9012%> (ø)

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed again at b0398943e2. Both findings from my last review are fixed: a priority manager created during key-generator injection and a priority-bearing FactoryBean product now preserve Spring's choice, including the configurations where grailsCacheManager depends on the cache-aware bean. The upgrade skill still matches the guide, and the trait remains unchanged.

Verification:

  • Ran ./gradlew :grails-cache:test --offline --console=plain --max-workers=2 on Java 21: 49 tests passed, including the 777-arrangement matrix and both MissingCacheSpec compilation modes.
  • Reran the four previous standalone reproducer configurations against the exact fallback source in this head, with the published 8.0.0 trait, Groovy 5.1.3 and Spring 7.0.11: all now preserve the original choice and start.
  • Ran additional isolated Spring-context probes for requesting-bean identity, lifecycle dependency tracking and non-singleton FactoryBean products. These expose the three issues below, which the current matrix does not cover.

I would address these before merging. The new fallback resolves the previous timing and product-priority problems, but the extra resolution pass does not preserve the requesting bean or product creation count, and returning a suggested value skips dependency registration. CI was still running when checked; no completed check was failing.

}
Probe probe = new Probe(descriptor)
try {
beanFactory.resolveDependency(probe, null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the requesting bean when probing the dependency. Passing null here changes Spring's candidate set: normal injection excludes the requesting bean and beans produced by its own factory methods before considering self-references. I reproduced this with grailsCacheManager implemented by a class extending ConcurrentMapCacheManager and implementing GrailsCacheManagerAware, beside one ordinary manager named other. Without the fallback, Spring excludes the manager itself and injects other. With this fallback, the probe sees two candidates and returns grailsCacheManager, so the manager is injected into itself. With allowCircularReferences=false, as in Boot's default configuration, the previously working context instead fails with BeanCurrentlyInCreationException. Please preserve the original requesting-bean context and add coverage for a cache-aware cache manager; the existing cyclic rows use a separate cache-aware bean and do not exercise self-reference exclusion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed: the probe ran without the requesting bean, so a cache-aware grailsCacheManager beside other was given itself, or failed to start with circular references disallowed.

Fixed in 5b6bfc7. There's no probe any more. Spring asks the candidate resolver's getLazyResolutionProxyIfNecessary(descriptor, requestingBeanName) right before it resolves a dependency, and for the trait's field the resolver now answers with the field's one resolution: doResolveDependency for that requesting bean. The only change is a descriptor whose resolveNotUnique takes grailsCacheManager where Spring can't choose and it's a candidate. So self-references are excluded exactly as before.

  • CacheAutoConfigurationSpec has your case, with circular references allowed and disallowed. grailsCacheManager gets other in both. With the pushed fallback, the first injected it into itself and the second failed to start.
  • The matrix has a cache-aware grailsCacheManager as a kind, and each row now checks what it gets against 8.0.0. Seven rows failed that with the pushed fallback.

// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Register the dependency when supplying the fallback manager. Returning the manager from getSuggestedValue makes Spring take the predefined-value path in doResolveDependency, which returns before adding the manager to autowiredBeanNames. Consequently AutowiredAnnotationBeanPostProcessor never registers the cache-aware bean as a dependent of its cache manager. I verified that getDependenciesForBean('service') is empty for the fallback, versus [grailsCacheManager] when ordinary primary selection injects the same manager. This affects lifecycle ordering: with a SmartLifecycle cache manager at phase 100 and a cache-aware SmartLifecycle service at phase 0, ordinary injection stops the service while the manager is still running; fallback injection stops the manager first and the service's stop callback sees it already stopped. Please use a resolution path that retains Spring's dependency registration, and cover lifecycle ordering as well as the injected instance.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed: the suggested-value path returned before Spring recorded the bean, so nothing was registered.

Fixed in 5b6bfc7. The fallback no longer goes through getSuggestedValue. The resolver runs the field's one resolution with its own autowiredBeanNames, adds grailsCacheManager where it falls back, and registers the requesting bean as depending on each of them with registerDependentBean, as AutowiredAnnotationBeanPostProcessor.registerDependentBeans does.

  • CacheAutoConfigurationSpec has your lifecycle case: a SmartLifecycle grailsCacheManager at phase 100 and a cache-aware SmartLifecycle service at phase 0, given grailsCacheManager through the fallback. The service is a dependent of grailsCacheManager and stops while it is still running. Both checks failed with the pushed fallback.
  • Every matrix row now compares getDependenciesForBean of the cache-aware bean with 8.0.0's, and requires grailsCacheManager there where it falls back. 74 rows failed that with the pushed fallback.

Comment on lines +187 to +189
boolean exists = beanFactory instanceof SingletonBeanRegistry &&
((SingletonBeanRegistry) beanFactory).containsSingleton(beanName)
exists ? super.resolveCandidate(beanName, requiredType, beanFactory) : NOT_CREATED

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid creating a non-singleton FactoryBean product twice. containsSingleton(beanName) only establishes that the FactoryBean itself exists; it does not mean its CacheManager product is a singleton. For an initialized FactoryBean<CacheManager> with isSingleton() == false, this call creates a product during the probe, then the ordinary dependency resolution creates another after getSuggestedValue returns null. I reproduced this with that factory registered first, a primary grailsCacheManager, and one cache-aware service: both versions inject the primary manager, but the factory's getObject() runs once without the fallback and twice with it. The extra product is discarded, which adds initialization side effects and can leak any resources that manager allocates. Please avoid replaying product creation and add a non-singleton-product regression that asserts invocation counts, not just the names of managers created.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed: getObject() ran twice, once for the probe and once for the injection.

Fixed in 5b6bfc7 by removing the probe. The field is resolved once, so a non-singleton factory is asked once, as in 8.0.0.

  • The matrix has a factory bean of new cache managers as a kind, and counts how many times each cache manager is created, not just which ones. A row fails if any is created more often than in 8.0.0, other than grailsCacheManager where it falls back. 131 rows failed that with the pushed fallback.
  • A separate feature is your exact case: the factory first, a primary grailsCacheManager, one cache-aware bean. It asserts getObject() runs once with the fallback, as without it, and that grailsCacheManager is 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.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. A repeated injection creates a new cache manager each time.

if (proxy != null || beanFactory == null || descriptor instanceof FallbackDescriptor || !isTraitField(descriptor)) {
return proxy
}
FallbackDescriptor fallback = new FallbackDescriptor(descriptor, beanFactory)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three prototype beans each get a cache manager. The first choice is already known, so the later beans should reuse it. Each one creates another manager. Remember the choice.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed. After a field's first resolution picks one bean, Spring's injection caches a shortcut to that bean's name, so a prototype's next instances only call getBean(name). The fallback answers the field itself, so Spring recorded no bean and cached just the descriptor, and every instance re-ran the full resolution. A factory bean of new cache managers among the candidates then made one per instance, where 8.0.0 made one for the first.

Fixed in 24e9f70. The resolver now remembers the choice the way the injection does:

  • When: after the field's resolution has taken one bean of the field's type.
  • Scope: by bean name and injection point, matching the scope of Spring's field cache.
  • After that: it resolves the field by that name, as long as the bean is still there and of that type.

Tests:

  • Every matrix arrangement now also creates three instances of a prototype cache-aware bean, and checks what they get and what they create against 8.0.0. With the previous fallback, 113 rows created more.
  • Two features pin your case with a factory bean of new cache managers: one beside a primary grailsCacheManager, one where Spring can't choose and the prototypes get grailsCacheManager. In both, the factory is asked once for the first prototype and not again.

Writing these also turned up a bug in the matrix's own counting, now fixed. A list difference dropped repeated creations of a cache manager also created at startup, so a repeat could go unnoticed.

…tion 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.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. After a reload, a bean still gets the cache manager from before the reload.

return proxy
}
List<Object> injectionPoint = Arrays.<Object>asList(beanName, descriptor)
String rememberedName = remembered.get(injectionPoint)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A reload registers the bean again and adds a cache manager that should be chosen first. The bean still gets the old manager, because the remembered choice is kept. Forget the choice when the bean is registered again.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed. Spring forgets its own record of a bean's fields when the bean is registered again: the bean factory resets the definition, and AutowiredAnnotationBeanPostProcessor.resetBeanDefinition drops the bean's injection metadata. My resolver kept its remembered choice, so after the reload the prototype still got the old cache manager.

Fixed in dc451a9. The resolver is now also a MergedBeanDefinitionPostProcessor, added to the bean factory together with it. When the bean factory resets a bean's definition, the resolver forgets what that bean's fields took, as the injection does, and the next injection resolves afresh.

A new feature in the matrix spec runs your sequence and compares it with 8.0.0: inject a prototype, add a cache manager marked primary and inject again, register the prototype again and inject again. It covers both the case where Spring chooses grailsCacheManager and the case where the fallback does. The choice is kept until the prototype is registered again and is then made afresh, giving the new primary, as 8.0.0's own cache does. With the pushed resolver, both cases still got grailsCacheManager after the reload.

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.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. A bean that is registered again still gets the cache manager from before the reload.

void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof DefaultListableBeanFactory) {
DefaultListableBeanFactory listable = (DefaultListableBeanFactory) beanFactory
if (!(listable.autowireCandidateResolver instanceof CandidateResolver)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A clone of the resolver is already installed. A new primary manager is added and the bean is registered again. The new instance still gets the old manager, because this clone is not told to forget its choice. Forget the choice when the bean is registered again.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed: a copy of the resolver in another bean factory with its own injection was never told of resets, so a prototype registered again there kept grailsCacheManager after a primary was added.

You've had to find these one at a time, so this time I compared the whole of the resolver's memory with Spring's own before pushing. That turned up four more differences, and 5637ca3 fixes all five:

  • Copies of the resolver. The resolver now remembers by the identity of the injection point Spring passes, held weakly, instead of by bean name and an equal descriptor. Spring's field injection passes the same descriptor again for a bean's next injection, and a reset throws that descriptor away. So the memory lasts exactly as long as Spring's, in any bean factory and for any copy of the resolver, with no reset notices needed.
  • A remembered cache manager removed and replaced kept its old name, where Spring stores the new choice.
  • The remembered cache manager was fetched with getBean outside Spring's resolution. A prototype @Bean taking an InjectionPoint then failed, and a remembered bean that failed was not re-resolved. It now goes through doResolveDependency as a shortcut, and on failure the field is resolved again and the new choice remembered.
  • AOT-generated injection (AutowiredFieldValueResolver) resolves the field every time with a new descriptor. It now misses the memory and resolves every time, as in 8.0.0.
  • Spring's null bean: the fallback no longer takes a grailsCacheManager whose factory method returns null. Dependents are registered only where Spring registers them, for a value or a required field.

Tests: your case is a row of the reload feature, in another bean factory with a copy of the resolver. New features cover the removal and replacement, a per-injection-point prototype cache manager, and three AOT-style resolutions, each against 8.0.0. The matrix adds grailsCacheManager as a fallback bean, not a default candidate, with a @Priority, and a null bean, for 1,596 arrangements. Every one of these failed against dc451a9.

One difference I know of and can't remove from this hook: where the field resolves to null, Spring resolves it once more after the resolver. That re-creates only a prototype cache manager whose factory method returns null.

…pring 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.
@testlens-app

testlens-app Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

🚨 TestLens detected 1 failed test 🚨

Failed Jobs without Test Failures

❌ CI / Hibernate7 Functional Tests (Java 25, indy=false)

Test Summary

Tip

Inspect all details with the TestLens CLI: testlens pr 16980

CI / Spring Security Config Functional Tests (bcrypt) > :grails-test-examples-spring-security-core-functional-test-app:integrationTest

Test Runs Flakiness
BCryptSpec ❌ 0% 🟢

🏷️ Commit: 5637ca3
▶️ Tests: 91966 executed
⚪️ Checks: 96/96 completed

Test Failures

BCryptSpec (:grails-test-examples-spring-security-core-functional-test-app:integrationTest in CI / Spring Security Config Functional Tests (bcrypt))
org.testcontainers.containers.ContainerLaunchException: Container startup failed for image selenium/standalone-chrome:4.49.0
	at org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:346)
	at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:317)
	at grails.plugin.geb.WebDriverContainerHolder.startContainer(WebDriverContainerHolder.groovy:296)
	at grails.plugin.geb.WebDriverContainerHolder.reinitialize(WebDriverContainerHolder.groovy:189)
	at grails.plugin.geb.GrailsContainerGebExtension.visitSpec_closure2(GrailsContainerGebExtension.groovy:82)
	at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:139)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
Caused by: org.testcontainers.containers.ContainerFetchException: Can't get Docker image: RemoteDockerImage(imageName=selenium/standalone-chrome:4.49.0, imagePullPolicy=DefaultPullPolicy(), imageNameSubstitutor=org.testcontainers.utility.ImageNameSubstitutor$LogWrappedImageNameSubstitutor@403cff1c)
	at org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1308)
	at org.testcontainers.containers.GenericContainer.logger(GenericContainer.java:666)
	at org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:328)
	... 6 more
Caused by: org.testcontainers.shaded.org.awaitility.core.ConditionTimeoutException: Condition with Lambda expression in org.testcontainers.images.RemoteDockerImage was not fulfilled within 2 minutes.
	at org.testcontainers.shaded.org.awaitility.core.ConditionAwaiter.await(ConditionAwaiter.java:167)
	at org.testcontainers.shaded.org.awaitility.core.CallableCondition.await(CallableCondition.java:78)
	at org.testcontainers.shaded.org.awaitility.core.CallableCondition.await(CallableCondition.java:26)
	at org.testcontainers.shaded.org.awaitility.core.ConditionFactory.until(ConditionFactory.java:1160)
	at org.testcontainers.shaded.org.awaitility.core.ConditionFactory.until(ConditionFactory.java:1129)
	at org.testcontainers.images.RemoteDockerImage.resolve(RemoteDockerImage.java:109)
	at org.testcontainers.images.RemoteDockerImage.resolve(RemoteDockerImage.java:35)
	at org.testcontainers.utility.LazyFuture.getResolvedValue(LazyFuture.java:20)
	at org.testcontainers.utility.LazyFuture.get(LazyFuture.java:41)
	at org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1306)
	... 8 more

Rerun Controls

Select tests to mute in this pull request:

  • BCryptSpec

Reuse successful test results:

  • ♻️ Only rerun the tests that failed or were muted before

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

5 participants