Skip to content

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

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

codeconsole wants to merge 33 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, takes the trait's field over from Spring's AutowiredAnnotationBeanPostProcessor. It uses the mechanism Spring uses to hand a member to another post-processor, as for @Resource:

  • The registrar: a post-processor added first registers on each bean definition, as externally managed, the field and every member Spring injects after it: the class's autowired methods, and the fields and methods of its subclasses. Spring's injection then leaves those alone. It finds them, in Spring's order, with an AutowiredAnnotationBeanPostProcessor of its own. A member that Spring's @Resource or persistence post-processors take first is left to them.
  • The injection: a post-processor ordered right after Spring's injects the field, once Spring has injected the members before it, and then has its own AutowiredAnnotationBeanPostProcessor inject the members after it. So each member is injected where Spring injected it, and an autowired method sees the field set.

It injects the field as Spring's own field injection does: one resolution by the bean factory for the bean being injected, the registration of the bean as depending on what it took, the shortcut Spring keeps for the next injection of the bean, its single retry where that fails, and its reset when the bean's definition is registered again or removed. The descriptor changes one thing:

  • Where Spring can choose, it chooses as it did, with all its rules: the only cache manager, the one marked primary, the one with the highest priority, a bean named like the field, a resolvable dependency, the only default candidate. It judges 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 the bean named grailsCacheManager, or the bean it is an alias of, is one of the cache managers it cannot choose between, is the field given that bean, unless it is Spring's null bean.

Spring's AOT processing generates the injection of every member from the class, the field included, in Spring's order, whatever is registered on the bean definition. Where the application runs that generated code, the post-processor instead wraps the bean factory's autowire candidate resolver. The wrapper answers the generated code's resolution of the field with the same resolution, which falls back where Spring cannot choose, and registers the bean as depending on what it took. The generated code resolves the field each time, so nothing is remembered. One difference remains there: where that resolution finds no cache manager, Spring resolves the field once more, which creates again only a prototype cache manager whose factory method returns null. Spring's generated injection registers the field for reflection.

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, also by an alias, is used as well. With grails.cache.enabled: false the plugin defines none, and nothing changes unless the application defines one.
  • The cache tags use grailsCacheManager by name, as before. So with a cache manager of the application's own marked primary, the annotations cache with that one and the tags with grailsCacheManager, as in 8.0.0.
  • 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. The generated code reads the cache manager once a call, for the check, the lookup and the report. Cache managers are told apart by identity, so two that are equal are each reported. 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.
    • Against 8.0.0, also:
      • the order of a cache-aware class's own injection around the field, in two prototype instances: an autowired method in the class, in a subclass and in a superclass, the class's own field and a subclass's field whose bean creates a cache manager, and a method injected by name with @Resource;
      • a context processed ahead of time, whose generated code is compiled and started, alone, beside a second cache manager and beside one marked primary;
      • a prototype registered again after a primary cache manager is added;
      • a remembered cache manager that is removed, when it was the only one and when it was primary beside grailsCacheManager, with the replacement depended on and kept;
      • a remembered prototype cache manager that fails, retried once;
      • a prototype cache manager made for its InjectionPoint;
      • a prototype cache manager that makes nothing, alone and as a primary one beside grailsCacheManager;
      • a bean named like the field, taken by that name beside a factory bean that fails;
      • a field that keeps what it remembers when grailsCacheManager is added;
      • seven arrangements with a dependency registered as resolvable.
    • 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 post-processors, and under AOT the resolver, are installed once and in order.
  • MissingCacheSpec creates annotated classes as beans, compiled statically and dynamically, beside a second cache manager. Each annotation and each eviction has a missing cache of its own and is reported once, and a key closure is not run for a missing cache. It also checks that the cache manager is read once a call, and that two equal cache managers are each reported.
  • CacheAutoConfigurationSpec covers the plugin's auto-configuration:
    • another cache manager beside the plugin's grailsCacheManager, beside one the application defines, and beside one given grailsCacheManager as an alias;
    • 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;
    • a service that uses its cache manager from an autowired method, alone and beside a second cache manager;
    • 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.

@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.
8.0.x added "More GSP tags HTML-encode the attribute values they write"
at the end of the upgrade guide's Grails 8.0.1 part, where the cache
section is too. Both are kept, the GSP section first, as it came first
on 8.0.x. The grails-upgrade skill merged without a conflict and holds
both entries.

@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 cache manager that is allowed to be empty is resolved twice.

remembered.put(new InjectionPointKey(descriptor, forgotten), autowiredBeanName)
}
}
return value

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 chosen cache manager comes from a prototype factory that returns nothing. Returning that here makes Spring resolve the dependency again, so the factory runs twice and a later result can be injected. Keep the empty result.

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, and it was the one difference my last reply named: where the field resolves to nothing, the resolver can only return null, and Spring then resolved the field once more. Spring's own resolveCandidate already asks a prototype factory twice when the first answer is nothing. So with a factory that makes nothing twice, 8.0.0 leaves the field empty, while the extra pass asked a third time and injected that.

Fixed in c1a74cd. When the resolver resolves the field to nothing, it notes that injection point for the thread. In Spring's resolution right after, isAutowireCandidate answers that no bean is a candidate for that injection point or for Spring's fallback match of it. So nothing is created and the field stays empty. The note ends when Spring asks whether the field is required, which ends that resolution, and with the next resolution of the field.

A new feature in the matrix spec injects a prototype cache-aware bean three times beside a prototype cache manager that makes nothing twice. It compares what is injected and how often the factory is asked with 8.0.0: nothing, then a new one each time, four asks. With 79329f2, the first injection got the third one made, and the factory was asked five times.

The resolver answers the field from getLazyResolutionProxyIfNecessary,
where null means no answer, so where the field's resolution found
nothing Spring resolved it once more. A prototype cache manager whose
factory had made nothing was then asked again, and what it made that
time was injected, where 8.0.0 left the field empty.

The resolver now notes, for the thread, the injection point it has just
resolved to nothing. In Spring's resolution after it, no bean is a
candidate for that injection point or for Spring's fallback match of it,
so nothing is created and the field stays empty; the note ends when
Spring asks whether the field is required, which ends that resolution,
and with the next resolution of the trait's field.

A feature injects a prototype cache-aware bean three times beside a
prototype cache manager that makes nothing twice, and compares what is
injected and how many times the factory is asked with 8.0.0: nothing,
then a new one each time, four asks. With the previous resolver the
first injection got the third one made, and the factory was asked five
times.

@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 cache manager registered as a resolvable dependency is still resolved twice when the first answer is empty.


@Override
boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
!resolvedToNothing(descriptor) && delegate.isAutowireCandidate(bdHolder, descriptor)

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 cache manager is registered as a resolvable dependency, and its factory returns nothing the first time and a manager the second. The field should stay empty. The factory runs twice and the second result is injected, because this only stops bean candidates. Keep the empty result there 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.

Thanks, confirmed: Spring's candidate lookup adds the resolvable dependencies before it looks at beans, without asking the candidate resolver, and an ObjectFactory is asked each time. Because the resolver answered the field from a hook before Spring's own resolution, an empty answer made Spring resolve the field a second time, and that lookup asked the factory again and injected what it made then.

Rather than patch that lookup too, 4438cb6 removes the second resolution altogether. There is no resolver hook any more. The trait's field is taken over from AutowiredAnnotationBeanPostProcessor the way Spring hands a member to another post-processor, as it does for @Resource:

  • a registrar added first registers the field on each bean definition as externally managed, which Spring's injection then leaves alone;
  • an injection ordered right after Spring's injects it, once the bean's other fields are injected.

It injects the field as Spring's own field element does: one resolution by the bean factory for the bean, the dependent registration, the shortcut it keeps for later injections, its single retry, and its reset when the definition is registered again. The only change is in the descriptor, which overrides resolveNotUnique to take grailsCacheManager where Spring cannot choose. So an empty result is resolved once, inside Spring's own resolution, and your factory is asked exactly as often as in 8.0.0.

The resolvable-dependency feature in the matrix spec now runs seven arrangements against 8.0.0, your case among them. They include a factory that makes nothing at first, one that always makes nothing, one that makes a cache manager each time beside grailsCacheManager alone, a primary prototype that makes nothing, and an object registered for every type. Where Spring can choose, or the field stays empty, they match 8.0.0. Where 8.0.0 failed because it could not choose, they get grailsCacheManager.

The resolver resolved the trait's field itself every time, so where that
found nothing Spring resolved the field once more, and anything the
second lookup asks for was asked twice. c1a74cd kept beans out of
that second lookup, but Spring also asks for every dependency registered
as resolvable there, which the candidate resolver is not asked about: a
resolvable cache manager whose factory made nothing at first was asked
again, and what it made then was injected.

The resolver now resolves the field only where Spring would find
grailsCacheManager and another cache manager bean among the candidates,
the only arrangement in which it can fail to choose with
grailsCacheManager among them, and no cache manager is registered as a
resolvable dependency. It tells from the bean names and definitions
Spring's own lookup reads first, and the types the resolvable
dependencies are registered for, read from the bean factory as Spring
keeps no public record of them. Everywhere else the field is left to
Spring, with everything that goes with its resolution, as in 8.0.0. So
are Spring's own kinds of injection point, such as the shortcut its
field injection keeps for a field it resolved alone, which the resolver
resolved outside Spring's resolution before.

A feature injects a prototype cache-aware bean three times beside a
resolvable cache manager in five arrangements against 8.0.0; the
previous resolver differed in four. Another keeps the cache manager a
field Spring resolved alone remembers when grailsCacheManager is added.
The empty-result feature gains an arrangement in which the resolver
resolves the field, a primary prototype that makes nothing beside
grailsCacheManager, which fails without the note c1a74cd added.
…e it cannot choose

The fallback answered the trait's field from a candidate resolver hook
that runs before Spring's own resolution, and so had to rebuild around it
what Spring's field injection does: the current injection point,
dependency registration, the remembered shortcut and its reset and
retry, empty results, resolvable dependencies, and a check of when to
act at all, read partly from a private field. Each rebuilt part differed
from Spring's somewhere: a stale remembered choice after a removal, a
retry before Spring's, a type scan without the injection point, a
resolvable dependency registered while resolving, an alias of
grailsCacheManager not recognised, Spring's name lookup skipped, and a
reflective read a native image may refuse.

The field is now taken over from AutowiredAnnotationBeanPostProcessor
the way Spring itself hands a member to another post-processor: a
registrar added first registers it on each bean definition as an
externally managed member, which Spring's injection then leaves alone,
and an injection ordered right after Spring's injects it, once the
bean's other fields are injected. It injects as Spring's field element
does, with one resolution by the bean factory for the bean, its
dependent registration, its shortcut, its single retry and its reset on
a new definition; the descriptor keeps the standard name lookup and
changes only resolveNotUnique, which takes grailsCacheManager, or the
bean it is an alias of, where Spring cannot choose and it is one of the
candidates. Spring's AOT processing, which runs the post-processors, so
leaves the field out of the injection it generates; an AOT processor
registers the field for reflection, for the injection to set it.

The matrix spec covers a remembered cache manager removed beside
grailsCacheManager, the single retry against 8.0.0, a bean named like
the field beside a factory bean that fails, resolvable dependencies of
seven kinds, AOT processing and the order of the post-processors;
CacheAutoConfigurationSpec a grailsCacheManager given as an alias.
…identity

The code the cache annotations generate read grailsCacheManager for the
check that there is one, again for the cache lookup, and a third time
for the report of a missing cache, so a getter that answers differently
from one read to the next could check one cache manager, look in
another, and report against a third or fail. It is now read once a call
into a local the three use. The report of a missing cache kept one entry
for each cache manager by equality, so a second cache manager equal to
the first was never reported; it now keeps them by identity, held
weakly.

MissingCacheSpec gives each annotation and each eviction a missing cache
of its own, so each is checked to report once, and counts the keys made,
which a missing cache must not make. New features check one read a call
and the report for two equal cache managers.
The guide said the tags and the annotations both cache with
grailsCacheManager, and that the annotations use it wherever no other
cache manager is primary or has a priority. The tags are given
grailsCacheManager by name, while the annotations are given what Spring
chooses by type, which it can also choose without a primary or a
priority, as the only default candidate, and grailsCacheManager only
where Spring cannot choose. The guide, the upgrade note and the
grails-upgrade skill now say so, and that with a primary cache manager
of the application's own the two cache in different cache managers, as
in 8.0.0.

@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 cache-aware bean runs an autowired method before its cache manager is set.

this.beanFactory = beanFactory instanceof DefaultListableBeanFactory ? (DefaultListableBeanFactory) beanFactory : null
}

/** Right after {@code AutowiredAnnotationBeanPostProcessor}, at {@code Ordered.LOWEST_PRECEDENCE - 2}. */

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 cache-aware bean has an autowired method that uses the cache manager. That method now runs before the field is set, so startup fails or the first use is not cached. Set the field before those methods run.

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, and it was wider than two cache managers. Spring injects a bean's fields first, then its methods, a superclass's before a subclass's, and the trait's fields come last among a class's own fields. My injection of the field ran after all of that, so an @Autowired method saw no cache manager even with only one in the context, and a subclass's own field was injected before the trait's.

Fixed in 8229d7b. The registrar now asks a private copy of Spring's autowiring post-processor which members it injects and in what order. It takes over the trait's field and every member after it: the class's autowired methods, and the fields and methods of its subclasses. The injection sets the field and then has Spring's own injection do those members, so each runs where it ran in 8.0.0. A member that Spring's @Resource or persistence post-processors take first is left to them.

  • The matrix spec runs an autowired method in the class and in a subclass, one in a superclass (still before the field, as in 8.0.0), the class's own field and a subclass's field whose bean creates a cache manager, and a method injected by name with @Resource. Each runs in two prototype instances, against 8.0.0.
  • CacheAutoConfigurationSpec has your case: a service that uses its cache manager from an autowired method, alone and beside a second cache manager.
  • With the pushed injection, the method rows failed with one cache manager too, as did the subclass-field row and both auto-configuration cases.

While checking the neighbours I found that Spring's AOT processing ignores the take-over. It generates the injection of every member from the class, so the generated code still injected the field the plain way and failed beside a second cache manager. The spec that said otherwise only checked the bean definition. Fixed in 40b69c8: when running generated code, the fallback steps into Spring's resolution of the field instead. The generated code keeps Spring's order of members. A new feature compiles the generated code and starts a context from it, against the same without the fallback.

@testlens-app

This comment has been minimized.

…t's field

Spring's own injection sets a bean's autowired fields, then its autowired
methods, a superclass's before a subclass's, and in a class that
implements the trait the trait's fields come last among its fields. The
trait's field was taken over and injected after all of that, so an
autowired method of a cache-aware class, or of its subclass, ran before
the field was set and saw no cache manager, with one cache manager as
much as with two, and a field of a subclass was injected before it.

The registrar now finds the members Spring injects, in its order, with an
AutowiredAnnotationBeanPostProcessor of its own, and takes over the field
and every member after it: the class's autowired methods and the fields
and methods of its subclasses. Spring injects those before the field as
it did, and the injection sets the field and then has its own
post-processor inject the members after it, so each member is injected
where it was. A member that Spring's @resource or persistence
post-processors take first is left to them, and a bean whose class is
not the one its injection was found for is left to Spring, which then
injects every member itself.

The matrix spec covers an autowired method in the class and in a
subclass, one in a superclass, which still runs before the field, the
class's own field and a subclass's field whose bean creates a cache
manager with a priority, and a method injected by name with @resource,
each in two prototype instances against 8.0.0;
CacheAutoConfigurationSpec covers a service that uses its cache manager
from an autowired method, alone and beside a second cache manager. With
the previous injection the rows of methods in the class and the
subclass failed, with a single cache manager too, as did the subclass's
field and both of CacheAutoConfigurationSpec's; the superclass, own-field
and @resource rows guard what was already as in 8.0.0.
Spring's AOT processing generates the injection of every member a bean's
class has, from the class, whatever another post-processor registered
on the bean definition, so the code it generated for a cache-aware bean
injected the trait's field itself, with Spring's plain resolution, and a
context run from that code failed to start beside a second cache
manager, as 8.0.0 did. The spec that said the field was left out of the
generated injection checked only the bean definition.

Where the application runs generated code, the post-processor now wraps
the bean factory's autowire candidate resolver instead of taking the
field over, and the wrapper answers the generated code's resolution of
the field with the resolution that falls back to grailsCacheManager,
registering the bean as depending on what it took. The generated code
resolves the field each time, and sets it among the other members in
Spring's order. The reflection hint for the field comes with Spring's
own generated injection, so the AOT processor that registered it is
gone.

The matrix spec processes a context ahead of time, compiles the code
it generates and starts a context from it, alone, beside a second cache
manager and beside one marked primary, against the same without the
fallback; with the previous commit the second failed to start.

@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. An inherited method still runs before the cache manager is set.

afterField.postProcessMergedBeanDefinition(all, beanType, beanName)
List<Member> members = new ArrayList<Member>(all.externallyManagedConfigMembers)
int at = members.indexOf(field)
List<Member> after = at < 0 ? [] : members.subList(at + 1, members.size()).findAll { Member member ->

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 subclass inherits an autowired method that uses the cache manager. That method runs before the field is set, so it sees no cache manager. Set the field before that method runs.

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