Repository navigation
Convert remaining plugin descriptors from doWithSpring() to beanRegistrar() - #15994
Merged
Merged
Conversation
…trar() Migrates the in-tree framework plugins off the deprecated doWithSpring() bean DSL onto the BeanRegistrar API, following the pattern established by the SiteMesh 3 (apache#15964) and scaffolding (apache#15966) conversions. Descriptors are now statically compiled where the remaining hooks allow it. Converted with a straight registrar (config reads move to the Spring Environment, constructor/property refs become supplier lookups): async, cache, converters, datasource, dbmigration (hibernate5 + 7), domain-class, events, fields, gorm-graphql, layout, markup views, json views, rest-transforms, url-mappings. Per-artefact bean definitions (controllers, interceptors, services) and the redis pool beans need definition-level features the BeanRegistry API cannot express: autowire-by-name, arbitrary scopes, destroy methods and dynamic property values. Those registrations move to dedicated BeanDefinitionRegistryPostProcessors registered through beanRegistrar(). They run with highest priority so their definitions are visible to Spring Boot auto-configuration conditions, matching the visibility the doWithSpring() drain gave them, and an existing definition always wins so applications can still override the beans by name. Notable adjustments preserving behaviour: - The interceptor handler adapter becomes the named bean grailsInterceptorHandlerInterceptorAdapter (previously an inner bean) so its @Autowired members, including the Interceptor[] array, are still injected. - The converters error marshaller registerers reference the existing named marshaller beans instead of duplicating them as inner beans, keeping the ApplicationContextAware callback. - RedisConfigurationUtil gains a BeanDefinitionRegistry-based configureService variant; the bean-builder closure form remains for existing consumers. - GrailsUnitTest.defineBeans(plugin) now also applies a plugin's beanRegistrar(), so test setup that passes converted plugin instances (converters, json views) keeps working. - The chainedTransactionManagerPostProcessor registration drops the unrefreshed-context transactionManager guard; the post-processor itself only acts when a transactionManager definition and multiple chainable managers exist. The plugin and web-plugin profile skeletons and the plugin developer guide now show beanRegistrar() instead of the deprecated hook. Still on doWithSpring() (deferred): CoreGrailsPlugin and GroovyPagesGrailsPlugin (abstract parent bean templates and XML namespace handlers - the resolver-pipeline linchpin), the hibernate/mongodb/neo4j plugins (their datastore SpringInitializers return bean DSL closures) and the spring-security suite (config-driven DSL throughout).
codeconsole
requested review from
jamesfredley,
jdaugherty,
matrei and
sbglasius
and removed request for
jamesfredley,
jdaugherty,
matrei and
sbglasius
July 17, 2026 17:07
codeconsole
marked this pull request as draft
July 17, 2026 17:09
The unit-level conversions passed but three descriptors broke at real application boot; unit tests using a bare bean factory did not exercise the failing paths. 1. GraphQL: the Schema bean's varargs MappingContext constructor was previously satisfied by Spring's implicit single-constructor autowiring (collecting every MappingContext bean). The supplier passed none, so generate() produced an empty schema and returns null when there are no query fields — leaving graphQLSchema a NullBean and failing every GraphQL app context. The supplier now resolves the MappingContext beans via the SupplierContext and passes them to the Schema constructor. 2. Interceptors: promoting the handler adapter from an inner bean to a top-level bean made WebUtils.lookupHandlerInterceptors (which collects every HandlerInterceptor bean via getBeansOfType) see it twice — once directly and once through the MappedInterceptor — so every interceptor ran twice (duplicated output, double redirects). The mapped interceptor and its inner adapter bean move into InterceptorBeanDefinitionsPostProcessor, restoring the inner-bean structure: the adapter is still fully autowired but is no longer a standalone HandlerInterceptor bean. 3. URL mappings / data source: building the grailsUrlMappingsHolder ProxyFactoryBean (reload mode) and the dataSource InstanceFactoryBean inside instance suppliers hid their produced types (UrlMappings / DataSource) from Spring's factory-bean type prediction, breaking by-type autowiring — e.g. DefaultLinkGenerator's UrlMappingsHolder — in development/reload mode (seen in the Forge scaffolding boot). Both move to dedicated post-processors that register the definitions the same way the original DSL did, keeping proxyInterfaces / the DataSource type as definition metadata so Spring can predict the type without instantiating. Verified: the graphql-docs-app integration test (real app boot) passes, and grails-interceptors / grails-url-mappings / grails-datasource / grails-data-graphql unit tests pass. The url-mappings and interceptor post-processors are covered by structural specs asserting the faithful definition shape (inner adapter bean, ProxyFactoryBean proxyInterfaces).
- Replace the reflection-based exception-mapping assertion in ControllersGrailsPluginSpec with a behavioral test that resolves an exception through the public resolveException API - Extract the shared redis connection-settings parsing and sentinel normalization into helpers used by both configureService variants so the DSL and registry paths cannot drift - Drop redundant safe-navigation in RedisBeanDefinitionsPostProcessor and note why the class is not statically compiled - Comment why dataSources/grails.redis subtrees are read through the Grails config instead of the Spring Environment
Move the 'exceptionHandler' (GrailsExceptionResolver) registration from the controllers plugin descriptor to ControllersAutoConfiguration, guarded with @ConditionalOnMissingBean, so an application- or plugin-defined exceptionHandler backs the default off cleanly instead of triggering a bean-definition override — the same treatment as the i18n localeResolver / messageSource defaults documented under "More Framework Beans Are Cleanly Overridable".
…ator Move the 'grailsCacheManager' and 'customCacheKeyGenerator' registrations from the cache plugin descriptor to a new GrailsCacheAutoConfiguration, guarded with @ConditionalOnMissingBean, so a bean contributed by the application or another plugin — for example a cache-provider plugin's cache manager — backs the default off cleanly instead of triggering a bean-definition override. Same treatment as the i18n and controllers defaults documented under "More Framework Beans Are Cleanly Overridable".
jdaugherty
approved these changes
Jul 18, 2026
jdaugherty
left a comment
Contributor
There was a problem hiding this comment.
Mostly minor issues that should be able to be fixed easily.
… auto-config, guard redis definitions - GrailsUnitTest.defineBeans(plugin) now applies a plugin's doWithSpring() DSL first and its beanRegistrar() second, mirroring the boot order, so a plugin defining both hooks gets both sets of beans and registrar beans win name conflicts (previously the first hook found was applied and the other silently skipped) - GrailsCacheAutoConfiguration is additionally gated on the plugin-contributed CachePluginConfiguration definition so it backs off entirely when the cache plugin is not active, instead of failing to resolve the configuration bean - The registry variant of RedisConfigurationUtil.configureService skips bean names that already have definitions, so existing definitions win as in the other converted post-processors
jdaugherty
approved these changes
Jul 18, 2026
jdaugherty
left a comment
Contributor
There was a problem hiding this comment.
We should merge this once the tests pass.
matrei
approved these changes
Jul 18, 2026
matrei
left a comment
Contributor
There was a problem hiding this comment.
LGTM. I have added some comments that I think would be improvements. I did not have time to go through all of the files today, so if willing, consider applying the same patterns to the rest of the files.
- Use @ConditionalOnBooleanProperty on the cache auto-configuration and construct the cache managers with named arguments - Bump grailsVersion to '8.0.0-SNAPSHOT > *' in every converted descriptor: they now require the Grails 8-only BeanRegistrar API - Restructure ControllerBeanDefinitionsPostProcessor with named-argument bean-definition construction and extracted resolve helpers - Drop the explicit BeanRegistry.Spec/SupplierContext closure parameters in all converted descriptors in favour of implicit it, and construct the converters marshaller registerers with named arguments - Use def for inferable local/field declarations across the new specs and Spock's with() for the converters bean assertions
✅ All tests passed ✅Test SummaryCI / Spring Security Tests (25) > :grails-test-examples-spring-security-core-misc-functional-test-app-group:integrationTest
🏷️ Commit: 76bdd8c Learn more about TestLens at testlens.app. |
codeconsole
added a commit
to codeconsole/grails-core
that referenced
this pull request
Jul 19, 2026
classes Plugin.beanRegistrar() (apache#15994) plus the before-autoconfiguration retiming (apache#15934) already give Grails a Spring-native, statically-compilable bean-registration mechanism that runs before Boot evaluates its @ConditionalOnMissingBean defaults. That solves bean registration winning against Boot's own conditional defaults, but beanRegistrar() output is inserted as a single hard cut point ahead of all Boot auto-configuration, ordered only relative to other Grails plugins by name. It has no way to express "run before this specific @autoConfiguration but after that one" the way a real @autoConfiguration(before = ..., after = ...) class can, against any other auto-configuration on the classpath, Grails-authored or third-party. @GrailsBeans closes that gap: a Groovy AST transformation compiles a doWithSpring()-style `beans = { bean(Type[, "name"]) { ... } }` closure into public @bean factory methods on a plain @autoConfiguration class, with `.conditionalOnMissingBean(Type...)` chaining and typed closure parameters becoming constructor-style method parameters. No closures, and nothing DSL-specific, survive into the compiled bytecode. Because the result is an ordinary @autoConfiguration class, it must be registered in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports like any other. Rather than hand-maintaining that file, this adds org.apache.grails.buildsrc.autoconfiguration-imports, a build-logic convention plugin that generates it by scanning a module's own compiled classes for @autoConfiguration - the same way META-INF/grails-plugin.xml is already generated from scanned *GrailsPlugin classes elsewhere in this build. - grails-beans-dsl: the @GrailsBeans annotation (grails.compiler.beans, alongside grails.compiler.GrailsCompileStatic) and GrailsBeansASTTransformation, with unit tests covering every generated-bytecode behaviour and every malformed-DSL error path. - grails-beans-dsl-example: a worked example (Greeter / FancyGreeter / LoudGreeter), including an end-to-end test that boots a bare @EnableAutoConfiguration application with zero explicit reference to the example class and confirms the beans are discovered purely from the generated imports file. - build-logic: the autoconfiguration-imports convention plugin, with fixture-compiling unit tests of its own. - grails-doc: documents @GrailsBeans alongside the existing beanRegistrar()/doWithSpring coverage, explaining when to reach for each.
codeconsole
added a commit
to codeconsole/grails-core
that referenced
this pull request
Jul 20, 2026
classes Plugin.beanRegistrar() (apache#15994) plus the before-autoconfiguration retiming (apache#15934) already give Grails a Spring-native, statically-compilable bean-registration mechanism that runs before Boot evaluates its @ConditionalOnMissingBean defaults. That solves bean registration winning against Boot's own conditional defaults, but beanRegistrar() output is inserted as a single hard cut point ahead of all Boot auto-configuration, ordered only relative to other Grails plugins by name. It has no way to express "run before this specific @autoConfiguration but after that one" the way a real @autoConfiguration(before = ..., after = ...) class can, against any other auto-configuration on the classpath, Grails-authored or third-party - and it has no equivalent of Boot's declarative @conditional* family beyond a single coarse fallback() primitive, since beanRegistrar() runs entirely before Boot even starts evaluating any autoconfiguration's conditions. @GrailsBeans closes that gap: a Groovy AST transformation that compiles a doWithSpring()-style `beans = { bean(Type[, "name"]) { ... } }` closure into public @bean factory methods on a plain @autoConfiguration class, with `.conditionalOnMissingBean(Type...)` chaining and typed closure parameters becoming constructor-style method parameters. No closures, and nothing DSL-specific, survive into the compiled bytecode, and the result gets the full Spring Boot @conditional* family for free since it is genuinely Boot's own machinery. Because the result is an ordinary @autoConfiguration class, it must be registered in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports like any other. Rather than hand-maintaining that file, this adds org.apache.grails.buildsrc.autoconfiguration-imports, a build-logic convention plugin that generates it by scanning a module's own compiled classes for @autoConfiguration - the same way META-INF/grails-plugin.xml is already generated from scanned *GrailsPlugin classes elsewhere in this build. @GrailsBeans may also be applied directly to a *GrailsPlugin.groovy class extending grails.plugins.Plugin, so bean definitions can live in the familiar plugin descriptor file instead of a separate class. In that case the compiled @bean methods land on a generated sibling <PluginClassName>AutoConfiguration class instead - a Plugin subclass is instantiated by DefaultGrailsPlugin via plain reflection, never as a Spring bean, so it cannot carry @bean methods or a meaningful @autoConfiguration annotation of its own - and any @autoConfiguration found on the plugin class moves onto that sibling. Every other Plugin lifecycle hook keeps working exactly as it does today. Omitting @autoConfiguration on the plugin class is a compile-time error rather than a silent runtime gap, since the generated sibling would otherwise never be processed by Boot. - grails-beans-dsl: the @GrailsBeans annotation (grails.compiler.beans, alongside grails.compiler.GrailsCompileStatic) and GrailsBeansASTTransformation, with unit tests covering every generated-bytecode behaviour, every malformed-DSL error path, and the Plugin-subclass sibling-generation behaviour (including the missing-@autoConfiguration error). grails-core is a test-only dependency, needed only so fixtures can genuinely extend Plugin; the transformation itself detects a Plugin superclass by fully-qualified name, not by type. - grails-beans-dsl-example: a worked standalone-class example (Greeter / FancyGreeter / LoudGreeter), including an end-to-end test that boots a bare @EnableAutoConfiguration application with zero explicit reference to the example class and confirms the beans are discovered purely from the generated imports file. - grails-beans-dsl-plugin-example: a separate module demonstrating the Plugin-embedded form, kept apart from grails-beans-dsl-example because grails-core being on a module's classpath at all activates Grails' own plugin-bootstrap ApplicationContextInitializer unconditionally (registered via spring.factories), which would have changed the other example's existing test behaviour. Includes the same style of end-to-end auto-discovery test. - build-logic: the autoconfiguration-imports convention plugin, with fixture-compiling unit tests of its own. - grails-doc: documents both forms of @GrailsBeans alongside the existing beanRegistrar()/doWithSpring coverage, explaining when to reach for each.
codeconsole
added a commit
to codeconsole/grails-core
that referenced
this pull request
Sep 25, 2026
…doWithSpring() Plugins and applications moved off the bean builder DSL to beanRegistrar() (apache#15934, apache#15994) and the beans DSL (apache#16019, apache#16292), but GrailsUnitTest still offered only doWithSpring(), and a test had no way to use the beans DSL at all. - beanRegistrar(): a BeanRegistrar for the test's context, drained where an application's is - after doWithSpring(), so it wins a name conflict with the DSL. - getConfigurationClasses(): configuration classes for the test's context, registered ahead of the framework's auto-configurations as an application's own configuration is, so an auto-configuration's @ConditionalOnMissingBean backs off from them. By default the static nested @configuration classes of the test and of the tests it extends, the convention Spring's own test support follows; a nested @GrailsBeans @configuration class is how a test uses the beans DSL. - getIncludePlugins() now brings in an included plugin's beans block too. The harness registered only org.grails auto-configurations, so a third-party plugin's generated FooAutoConfiguration never reached a unit test, and defineBeans(plugin) cannot apply it after the context has refreshed. - doWithSpring() is deprecated, matching Plugin and GrailsApplicationLifeCycle. The unit testing guide leads with the new hooks; the upgrade guide and What's New note the deprecation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Continues the migration of in-tree framework plugins off the deprecated
doWithSpring()bean DSL onto the SpringBeanRegistrarAPI (deprecated by #15934), following the SiteMesh 3 (#15964) and scaffolding (#15966) conversions. Descriptors are now statically compiled where the remaining lifecycle hooks allow it.17 descriptors converted:
Environment; constructor/property refs become supplier-context lookups)BeanRegistrycan't express)Why some registrations need a post-processor
Per-artefact controller/interceptor/service beans autowire by name and use arbitrary scopes; the redis pool beans need a
destroymethod and dynamic property values. None of these can be expressed through theBeanRegistry.SpecAPI, so their definitions move to dedicatedBeanDefinitionRegistryPostProcessors registered throughbeanRegistrar(). They run atPriorityOrderedhighest precedence so their definitions are visible to Spring Boot auto-configuration conditions — the same visibility thedoWithSpring()drain gave them — and an existing definition for a bean name always wins, so applications (or other plugins) can still override the beans.Behavioural parity notes
grailsInterceptorMappedInterceptor, as in the original DSL: inner beans are still fully autowired — the adapter's@Autowired Interceptor[]is injected — but are not returned bygetBeansOfType, soWebUtils.lookupHandlerInterceptorsdoes not collect the adapter a second time and interceptors do not run twice. Its definition (and the per-interceptor beans) is contributed byInterceptorBeanDefinitionsPostProcessor.ApplicationContextAwarecallback.RedisConfigurationUtilgains aBeanDefinitionRegistry-basedconfigureServicevariant; the bean-builder closure form remains for existing consumers.GrailsUnitTest.defineBeans(plugin)now also applies a plugin'sbeanRegistrar(), so test setup that passes converted plugin instances (converters, JSON views) keeps working.chainedTransactionManagerPostProcessorregistration drops the unrefreshed-contexttransactionManagerguard; the post-processor itself only acts when atransactionManagerdefinition and multiple chainable managers exist.The
pluginandweb-pluginprofile skeletons and the plugin-developer guide now showbeanRegistrar()instead of the deprecated hook.Overridable framework defaults moved to auto-configuration
Two conversions surfaced framework defaults that applications and plugins override by bean name. Because the plugin registration phase drains framework plugins before application plugins, keeping them as registrar-time registrations meant any such override triggered a bean-definition override (with Spring's startup notice). These defaults now register through auto-configuration guarded with
@ConditionalOnMissingBean— the same treatment as the i18n and URL-mappings beans under "More Framework Beans Are Cleanly Overridable" — so a bean contributed by the application or another plugin simply wins and the default is never registered:exceptionHandler(GrailsExceptionResolverwith theException→/errormapping) moved from the descriptor to the existingControllersAutoConfiguration.grailsCacheManager(config-driven selection viagrails.cache.cacheManagerpreserved) andcustomCacheKeyGeneratormoved from the descriptor to a newGrailsCacheAutoConfiguration, gated ongrails.cache.enabledexactly like the registrar was. Cache-provider plugins replacegrailsCacheManagerby name, so this previously produced an override notice at every boot with a provider installed.The upgrade guide's "More Framework Beans Are Cleanly Overridable" list now includes both.
Still on
doWithSpring()(deferred to follow-up PRs)CoreGrailsPluginandGroovyPagesGrailsPlugin— abstract parent bean templates (abstractGrailsResourceLocator,abstractViewResolver) and an XML-namespace component-scan; the resolver-pipeline linchpin.SpringInitializers return bean-DSL closures, so conversion means reworking the initializers.Testing
*GrailsPluginSpec/*PostProcessorSpecfor every converted descriptor, exercising the registrar throughBeanRegistryAdapter.ControllersAutoConfigurationSpecand a newGrailsCacheAutoConfigurationSpec; the full-appgrails-test-examples-cacheunit + integration suites andgrails-spring-security-rest-grailscache(agrailsCacheManagerconsumer) pass.grails-test-suite-web,-uberand-persistence(the full-lifecycle consumers of these plugins)../gradlew codeStyleand./gradlew clean aggregateViolationsare clean across all four analysers (Checkstyle, CodeNarc, PMD, SpotBugs).