Repository navigation
8.0 (fix): Inject the beans generated ahead of time only once - #16709
jdaugherty merged 12 commits into
Conversation
An application running on generated artifacts has the annotation processors registered again, for beans built by a supplier and declared as an interface. Those processors also injected every bean the generated code had already injected, so a side-effecting @Autowired method ran twice: every executor's metrics were registered a second time on a JVM running with -Dspring.aot.enabled=true. The definitions the generated code contributed are now recorded as the context is initialized, before any plugin declares a bean, and the processors registered again leave them alone. They are also declared with suppliers, so creating them needs no reflection. (cherry picked from commit 8bfca2b)
The generated code injects a bean only through the annotated members of the type its definition declares. A factory method declaring an interface, as the link generator's does, leaves every annotated member of the class it returns to the annotation processors Grails registers again. Skipping every generated bean left the link generator without its URL mappings, so the AOT example application failed to render a link. The processors now leave a generated bean alone only when it is of exactly the type its definition declares, or the subclass Spring generates for a configuration class. A side-effecting @Autowired method on such a bean still runs once. (cherry picked from commit f2a1277)
They were written for 9.0 and are backported here.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16709 +/- ##
==================================================
+ Coverage 62.1568% 62.1809% +0.0241%
- Complexity 26860 26908 +48
==================================================
Files 2237 2241 +4
Lines 110588 110743 +155
Branches 20189 20215 +26
==================================================
+ Hits 68738 68861 +123
- Misses 32597 32617 +20
- Partials 9253 9265 +12
🚀 New features to boost your workflow:
|
jdaugherty
left a comment
There was a problem hiding this comment.
Faithful backport of 8bfca2b and f2a1277 from #16180: only the @since lines differ, it merges cleanly on current 8.0.x, and CI is green.
I read the rule the processors apply against Spring 7.0.9. DefaultBeanRegistrationCodeFragments emits new RootBeanDefinition(userClass) and setTargetType(getUserClass(beanType)), and both AOT contributions (AutowiredAnnotationBeanPostProcessor, InitDestroyAnnotationBeanPostProcessor) key their work off RegisteredBean.getBeanClass(), the user class of that same type, so "the instance's user class is the declared type" is exactly the condition under which the generated code injected the bean and recorded its lifecycle methods. The CGLIB case in GeneratedBeanDefinitionsSpec matches what the generator emits: the user class, not the proxy. Boot 4.1.1 inserts the generated initializer at index 0 and sorts stably, so the unordered GrailsPluginLifecycleInitializer records after it and before any plugin bean.
Four non-blocking notes inline: the javadoc's claim about a bean of another class is exact only for an interface (a declared superclass is still injected twice through its own members; verified with a fixture), postProcessBeforeDestruction has no test, the initializer's "before any other" overstates Boot's ordering, and the AOT guide section still says these two processors are absent.
For the merge-up: #16180 carries the same two commits with @since 9.0. Once this reaches 9.0.x that branch needs them dropped, or its @since lines reconciled to 8.0.1.
GeneratedArtifactsCommonAnnotationBeanPostProcessor stands down in postProcessBeforeDestruction for a bean the generated code created, so the destruction method that code recorded on the definition runs once, called by the container. Nothing exercised that. The fixture now has a @PreDestroy method, which the generated definition records as the generated code does, and a @resource setter, so the common processor's injection is covered as well as the autowired one's. Without the override the destruction method runs twice.
The generated code injects a bean through the annotated members of the type its definition declares. For a factory method declaring a superclass of the class it returns, the processors registered again for generated artifacts then injected the whole class, so the superclass's @Autowired and @resource members ran twice, and so did an @Autowired override of one, which the generated code had already called. Before processing such a bean, the processors now mark those members on its definition as configured from outside, the mechanism Spring uses to keep two processors from injecting one member, and inject only what the subclass adds. Spring's own processor, as the code was generated with, finds the members on the declared type, and the overrides in the bean's class are marked with them. A factory method declaring an interface has no members to mark, so its bean is processed fully, as before. Lifecycle methods are unchanged: the processor calls them all and marks them, so the container skips the ones the generated code recorded.
Spring Boot does not run the generated initializer before every other: it adds it ahead of the application's initializers and sorts them stably, so an initializer with an order runs before it. Recording is correct as long as none of those registers a bean definition, which holds for Spring Boot's own. Say that rather than the stronger claim.
The guide listed the autowired and common annotation processors among the infrastructure an AOT-processed application no longer has. Grails has registered them again since b1611e3, for the annotated members the generated code cannot see: those of a bean a plugin registers at runtime, and those of a bean declared as an interface and built by a supplier. They now leave the members the generated code injected to that code.
|
Where this stands at 1d6f73b, after jdaugherty's and James's reviews: How a generated bean is recognized. The code generated for each definition, inner beans included, calls Injection. For a bean whose merged definition carries the mark, the processors register that type's members as externally managed config members, along with their overrides resolved through generic bridges. Then they process the bean as Spring does. The instance the generated code created is injected only through what its class adds. Any other instance under that name, such as one from Lifecycle. The common processor calls annotated init and destroy methods for every instance. The names the generated code recorded for them are taken off its definitions when the processors are registered. Tests.
All 11 pass. Against the previous design, 5 fail: the inner bean, the early bean, and the three other-instance cases. Removing any one of the new pieces makes the cases it guards fail. Verified. The grails-core suite and the style check pass on both branches. The AOT example application starts from regenerated code with 383 marked definitions and no warnings. On #16180, the native-i18n image builds with GraalVM 25 and passes every check. Merge-up. #16180 carries the same commits as |
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving. The ordinary top-level generated bean is no longer injected twice, and the guide is right that the two processors are registered again at runtime. The snapshot still treats the wrong beans as already generated, so some beans are injected zero times and some are still injected twice.
A subclass that overrides a generic superclass's annotated setter with the actual type also gets a bridge taking the erased one. The generated code calls the setter through that bridge, and ClassUtils resolves the superclass method to the bridge too, so the bridge was marked. Spring's autowiring metadata skips bridges and keeps the override, which was then injected a second time. BridgeMethodResolver resolves to the method the bridge leads to, which is the member the processor holds.
The definitions the generated code contributed were taken from a snapshot of the bean factory as the context was initialized, and a bean was left alone when its definition was in the snapshot and its class was the type the definition declared. That was wrong three ways: - The snapshot held every definition registered by then, so a bean an initializer ordered ahead of the generated one declared was taken for a generated one, and nobody injected or initialized it. - An inner bean is not in the registry, so it was never in the snapshot, and was injected twice. - The decision went by name and type, not by instance. Another instance under a generated bean's name, as configureBean and the Hibernate bean container create, was left uninjected, and initializeBean skipped its @PostConstruct method. The code generated for each definition, an inner bean's included, now marks it as it returns it. GeneratedInjectionBeanRegistrationAotProcessor has it call GeneratedBeanDefinitions.markGenerated, which names the type whose members that code injects and has the instance supplier record, by identity, each instance it creates. The processors read the mark from the merged definition they are given and mark that type's members, and their overrides, as configured from outside. They then process every bean: an instance the generated code created only through what its class adds, and any other instance in full, through a plain processor whose metadata carries no marks. Lifecycle methods are no longer skipped. The common processor calls the annotated ones for every instance, as on a context without generated code, and the names the generated code recorded for them are taken off its definitions when the processors are registered. Left on, they made configureBean call them twice, since it works on a copy of the definition that keeps the recorded names but not what the processor called. The snapshot, and recording it in GrailsPluginLifecycleInitializer, are gone. GeneratedArtifactsInjectionSpec generates, compiles and runs the code for each case and counts every call; the cases that the snapshot, the name check and the inner bean got wrong fail without this change.
jamesfredley
left a comment
There was a problem hiding this comment.
The four earlier comments are fixed. Generated code marks only the definitions it wrote, a fresh instance of a generated bean name is injected, nested beans are not injected twice, and the generic override is marked instead of the bridge. The targeted grails-core specs passed: 34 tests, 0 failures. Not approving yet because the fallback processors still inject a dual-annotated member independently.
Another instance of a generated bean, one handed to configureBean, is injected in full by Spring's own processors, but each of the two did so on its own. Spring runs the common processor first on a bean's definition, and the autowired processor then leaves to it a member the common one registered there. Without a shared definition, a field or method annotated with both @resource(name = ...) and @Autowired was injected twice, so autowiring replaced the named resource with the primary bean, and a method annotated so ran twice. The autowired processor now has Spring's common processor mark its members on a definition for the instance first, and processes that definition itself before injecting, as Spring would. The regression configures such an instance and checks it against a bean declared any other way: the named resource, and the method called once.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving yet. The ordinary-instance case from the last comment is fixed: a field with both @Resource(name = "named") and @Autowired keeps the named resource, and a dual-annotated method runs once. The targeted AOT specs passed, 35 tests. A CGLIB-enhanced instance of that same bean still loses the exclusion.
The autowired processor prepared the definition for another instance of a generated bean under the instance's user class, but the injection that follows looks the metadata up under the instance's class. For a CGLIB subclass handed to configureBean, the two differ, so the metadata was rebuilt without the members the common processor had taken, and a member annotated with both @resource(name = ...) and @Autowired was injected twice again. The definition is now prepared under the instance's class. The regression configures a CGLIB-enhanced instance as well as a plain one.
🚨 TestLens detected 62 failed tests 🚨Failed Jobs without Test Failures❌ CI / Hibernate7 Functional Tests (Java 25, indy=false) Test SummaryTip Inspect all details with the TestLens CLI: Groovy Snapshot Canary Build / Build Grails (shard 0) > :grails-test-examples-mongodb-hibernate5:test
Groovy Snapshot Canary Build / Build Grails (shard 1) > :grails-data-mongodb-core:test (first 40 of 58)
Groovy Snapshot Canary Build / Build Grails (shard 2) > :grails-data-mongodb-spring-boot:test
🏷️ Commit: 20f2cb2 Test Failures (first 10 of 62)BookFongoSpec (:grails-test-examples-mongodb-hibernate5:test in Groovy Snapshot Canary Build / Build Grails (shard 0))AttachMethodSpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))BuiltinUniqueConstraintWorksWithTargetProxiesConstraintsSpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))CircularOneToManySpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))CommonTypesPersistenceSpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))ConstraintsSpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))CriteriaBuilderSpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))CrossLayerMultiDataSourceSpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))CrossLayerMultiTenantMultiDataSourceSpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))CrudOperationsSpec (:grails-data-mongodb-core:test in Groovy Snapshot Canary Build / Build Grails (shard 1))Rerun Controls (first 20 of 62)Select tests to mute in this pull request:
Reuse successful test results:
Click the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
jamesfredley
left a comment
There was a problem hiding this comment.
Approving. The CGLIB comment is fixed. Fallback injection is prepared under bean.getClass(), so the metadata lookup matches and a dual-annotated member on a CGLIB-enhanced instance keeps the named resource and runs once. The focused AOT specs passed.
Backports the double-injection fix from #16180, which carries the same commits.
When an application runs on generated artifacts (
-Dspring.aot.enabled=true), Grails registers Spring's@Autowiredand common-annotation processors a second time. They are there for the annotated members the generated code cannot see: those of the beans plugins register as the application starts, and those of beans declared as an interface, like the link generator. But those processors also injected every bean the generated code had already injected, so a side-effecting@Autowiredmethod ran twice. The AOT example application logs this on startup:The code generated for each bean definition, inner beans included, now marks the definition as it returns it (
GeneratedInjectionBeanRegistrationAotProcessor). The mark names the type whose members that code injects, and the definition's instance supplier records each instance it creates. With that:configureBeanor the Hibernate bean container creates, is injected in full, as Spring injects any bean. A member annotated with both@Resourceand@Autowiredis left to the common processor, which comes first.@PostConstructand@PreDestroymethods are called by the common processor for every instance. The names the generated code recorded for them are taken off its definitions when the processors are registered, so the container doesn't call them a second time. That includes underconfigureBean, which works on a copy of the definition.The processors are also created through suppliers rather than reflectively. The AOT guide no longer lists them among the infrastructure an AOT-processed application lacks, and says what they are registered for.
GeneratedArtifactsInjectionSpecgenerates the code for each case, compiles it, starts a context from it, and counts every call.Nothing changes for an application that does not run on generated artifacts.