From 0760a7c13cf32628839a4f4572b12888faf8430d Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 11 Sep 2026 11:03:10 -0700
Subject: [PATCH 01/39] test: add an end-to-end module verifying message
bundles resolve in a native image
AOT processing on a JVM cannot falsify a resource hint: every bundle on a JVM
classpath is readable whether it was registered or not, so a missing hint shows
up only in a compiled image. The application resolves one code from each way a
bundle reaches the message source - the application's own bundle, a namespaced
plugin bundle, and a dotted base name the application configured - in English
and in a locale variant, plus an unknown code to prove MessageSourceProperties
bound as a whole.
This belongs on 9.0.x rather than 8.0.x. Dynamic Groovy in an image needs both
GROOVY-12234's AOT link mode, which ships in the 6.0.0-beta-2 this branch pins
and in no 5.x release, and invokedynamic, which this branch compiles with by
default and which 8.0.x deliberately forces off for published artifacts. Either
one missing is fatal to the image, so native image is not a Grails 8 capability.
The JVM half runs in check and needs nothing special. The native half is opt-in
behind -PnativeTests because it needs a GraalVM toolchain and minutes of CPU.
---
end-to-end/README.md | 64 ++++++++++
end-to-end/gradle.properties | 5 +
end-to-end/native-i18n-plugin/build.gradle | 37 ++++++
.../i18n/native-messages.properties | 19 +++
.../i18n/native-messages_fr.properties | 19 +++
.../plugin/NativeMessagesGrailsPlugin.groovy | 32 +++++
end-to-end/native-i18n/build.gradle | 102 +++++++++++++++
.../grails-app/conf/application.yml | 27 ++++
.../grails-app/i18n/messages.properties | 19 +++
.../grails-app/i18n/messages_fr.properties | 19 +++
.../init/nativei18n/Application.groovy | 118 ++++++++++++++++++
.../resources/config/i18n/custom.properties | 19 +++
.../config/i18n/custom_fr.properties | 19 +++
end-to-end/settings.gradle | 5 +
14 files changed, 504 insertions(+)
create mode 100644 end-to-end/native-i18n-plugin/build.gradle
create mode 100644 end-to-end/native-i18n-plugin/grails-app/i18n/native-messages.properties
create mode 100644 end-to-end/native-i18n-plugin/grails-app/i18n/native-messages_fr.properties
create mode 100644 end-to-end/native-i18n-plugin/src/main/groovy/nativei18n/plugin/NativeMessagesGrailsPlugin.groovy
create mode 100644 end-to-end/native-i18n/build.gradle
create mode 100644 end-to-end/native-i18n/grails-app/conf/application.yml
create mode 100644 end-to-end/native-i18n/grails-app/i18n/messages.properties
create mode 100644 end-to-end/native-i18n/grails-app/i18n/messages_fr.properties
create mode 100644 end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
create mode 100644 end-to-end/native-i18n/src/main/resources/config/i18n/custom.properties
create mode 100644 end-to-end/native-i18n/src/main/resources/config/i18n/custom_fr.properties
diff --git a/end-to-end/README.md b/end-to-end/README.md
index 7d2dc6cfb67..5a5d5f96767 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -35,6 +35,8 @@ applications at via `GRAILS_REPO_URL`.
| `legacy-g7-command-plugin` | A **standalone build**, not part of this one. Compiles against published Grails 7 / Groovy 4 to produce a genuine precompiled `grails.dev.commands.ApplicationCommand` binary. |
| `legacy-commands-plugin` | A Grails 8 plugin whose legacy commands are recompiled under Groovy 5. |
| `legacy-commands` | A Grails 8 application that consumes both and runs their commands through the registry. |
+| `native-i18n` | An application that resolves messages from three kinds of bundle, on a JVM always and inside a GraalVM binary when asked. |
+| `native-i18n-plugin` | A plugin shipping a namespaced message bundle (`native-messages.properties`), with a multi-word plugin name. |
| `spring-dependency-management` | A Grails 8 application that manages its versions with the legacy `io.spring.dependency-management` plugin instead of the Grails Gradle plugin's native `platform(grails-bom)`, as an upgraded Grails 7 application does. |
| `taglib-index-incremental` | Builds a Grails 8 application **twice, without a clean**, to prove a renamed or deleted tag library cannot survive in the published tag library index. Incremental behaviour is the whole point, so it cannot be expressed by a project the core build builds once for itself. |
@@ -51,6 +53,68 @@ published yet (a reproducible release build, or a fresh release branch whose ver
published), and otherwise silently fell back to whatever the Apache snapshot repository happened to
hold rather than the working tree.
+## Native image verification
+
+`native-i18n` exists because AOT processing on a JVM cannot falsify a resource hint. Every bundle on
+a JVM classpath is readable whether it was registered or not, so a missing hint shows up only in a
+compiled image — as a code resolving to itself, for a message that resolved perfectly in every test.
+
+The application resolves one code from each way a bundle reaches the message source, and only the
+first is covered by Spring Boot's own hints, which register the two hardcoded patterns
+`messages.properties` and `messages_*.properties` and derive nothing from the configured base names:
+
+| Bundle | Base name | Why it is here |
+|---|---|---|
+| the application's own | `messages` | The case Boot already covers, as a control. |
+| the plugin's | `native-messages` | Namespaced, so Boot's patterns never reach it. The plugin name is multi-word, so this also covers the descriptor's hyphenated spelling being matched against the plugin's camel-case one. |
+| one the application configured | `config.i18n.custom` | Outside `grails-app/i18n`, and written dotted, so it also proves the base name is converted to `config/i18n/custom` before being registered. |
+
+Each is resolved in English and in a locale variant. The locale half is the assertion that would
+fail if the hints registered *bundles* rather than resource *patterns* and the image were built with
+a narrower locale set than the bundles cover — the open question recorded in
+https://github.com/apache/grails-core/issues/16176.
+
+```bash
+cd end-to-end
+./gradlew :native-i18n:check # the JVM half, part of `check`
+./gradlew :native-i18n:check -PnativeTests # adds the native half
+```
+
+The JVM half runs in `check` and needs nothing special. It cannot falsify a hint; its value is as a
+fixture guard, keeping the bundles and the assertions from drifting apart. The native half is opt-in
+because it needs a GraalVM toolchain and minutes of CPU, not because it is expected to fail.
+
+### Why this runs here and not on 8.0.x
+
+Dynamic Groovy in a native image needs two things this branch has and 8.0.x deliberately does not:
+
+| | 8.0.x | here |
+|---|---|---|
+| `groovy.version` | 5.1.2 | 6.0.0-beta-2, which carries [GROOVY-12234](https://issues.apache.org/jira/browse/GROOVY-12234)'s AOT link mode for indy dispatch |
+| framework invokedynamic | forced off in `CompilePlugin`, because Groovy 5's indy default is a large runtime regression for dynamic Groovy (#15293) | Groovy's default, which is on |
+
+Without the AOT link mode, indy-compiled Groovy cannot link in an image: the runtime invokes
+`IndyInterface`'s bootstrap method without its `` having run, so a `static final` handle is
+still null and it fails as `BootstrapMethodError: NullPointerException` at
+`IndyInterface.makeBootHandle`. Without invokedynamic at all, Groovy classes carry a `CallSiteArray`
+and define call-site classes as they run, which an image forbids: `UnsupportedFeatureError: Tried to
+define class`, naming a class nobody wrote. Either one on its own is fatal, which is why native
+image is not a Grails 8 capability and this module is not on that branch.
+
+### What it needs
+
+**A GraalVM JDK, and not necessarily the one that published the framework.** `GRAALVM_HOME` and
+`JAVA_HOME` must point at a GraalVM before the image is built; `toolchainDetection = false` makes the
+plugin honour it rather than resolving a toolchain, so the publish JDK and the image JDK do not have
+to agree. Use GraalVM 25 or later: on the 21 line `nativeCompile` fails during "Initializing" with
+`Could not find target method: ...IndyInterface.invalidateSwitchPoints()`, because GraalVM's bundled
+Groovy substitution targets a method Groovy 4+ removed
+([oracle/graal#10200](https://github.com/oracle/graal/issues/10200), fixed in the 25 line). What must
+not happen is publishing on a JDK *newer* than the one the image is built with: `GroovyCompile` has
+no `release` option, so the Groovy sources in `grails-gradle` are compiled for the running JDK, and a
+newer class file version makes the image fail at *configuration* time, naming a framework class as
+though the framework had regressed.
+
## JDKs
The Grails 7 half declares the JDK it needs in a `.sdkmanrc`, rather than a Gradle toolchain, so that
diff --git a/end-to-end/gradle.properties b/end-to-end/gradle.properties
index 2803e610281..7c57e557847 100644
--- a/end-to-end/gradle.properties
+++ b/end-to-end/gradle.properties
@@ -23,3 +23,8 @@ org.gradle.jvmargs=-Dfile.encoding=UTF-8 -Xmx5G
org.gradle.configuration-cache=false
org.gradle.caching=true
org.gradle.parallel=true
+
+# GraalVM Gradle plugin, used only by the opt-in native verification in native-i18n. It lives here
+# rather than in dependencies.gradle because nothing the framework publishes depends on it - it is a
+# build plugin for one fixture in this build, not a managed coordinate of the BOM.
+graalvmBuildtoolsVersion=1.1.12
diff --git a/end-to-end/native-i18n-plugin/build.gradle b/end-to-end/native-i18n-plugin/build.gradle
new file mode 100644
index 00000000000..cc46af6e7b6
--- /dev/null
+++ b/end-to-end/native-i18n-plugin/build.gradle
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+plugins {
+ id 'org.apache.grails.buildsrc.properties'
+ id 'org.apache.grails.buildsrc.dependency-validator'
+ id 'org.apache.grails.buildsrc.compile'
+ id 'org.apache.grails.gradle.grails-plugin'
+}
+
+version = '0.0.1'
+group = 'nativei18n.plugin'
+
+dependencies {
+ implementation platform("org.apache.grails:grails-bom:$projectVersion")
+ implementation 'org.apache.grails:grails-core'
+}
+
+apply {
+ from rootProject.layout.projectDirectory.file('../gradle/grails-extension-gradle-config.gradle')
+}
diff --git a/end-to-end/native-i18n-plugin/grails-app/i18n/native-messages.properties b/end-to-end/native-i18n-plugin/grails-app/i18n/native-messages.properties
new file mode 100644
index 00000000000..e67752beacb
--- /dev/null
+++ b/end-to-end/native-i18n-plugin/grails-app/i18n/native-messages.properties
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+native.plugin.greeting=hello from the plugin bundle
diff --git a/end-to-end/native-i18n-plugin/grails-app/i18n/native-messages_fr.properties b/end-to-end/native-i18n-plugin/grails-app/i18n/native-messages_fr.properties
new file mode 100644
index 00000000000..6eac12032c7
--- /dev/null
+++ b/end-to-end/native-i18n-plugin/grails-app/i18n/native-messages_fr.properties
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+native.plugin.greeting=bonjour depuis le paquet du plugin
diff --git a/end-to-end/native-i18n-plugin/src/main/groovy/nativei18n/plugin/NativeMessagesGrailsPlugin.groovy b/end-to-end/native-i18n-plugin/src/main/groovy/nativei18n/plugin/NativeMessagesGrailsPlugin.groovy
new file mode 100644
index 00000000000..316af08c8fd
--- /dev/null
+++ b/end-to-end/native-i18n-plugin/src/main/groovy/nativei18n/plugin/NativeMessagesGrailsPlugin.groovy
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package nativei18n.plugin
+
+import grails.plugins.Plugin
+
+/**
+ * A plugin whose Grails name is multi-word, so its bundle exercises both halves of the naming:
+ * the descriptor records the hyphenated {@code native-messages}, while the plugin the application
+ * discovers reports the logical {@code nativeMessages}.
+ */
+class NativeMessagesGrailsPlugin extends Plugin {
+
+ def grailsVersion = '9.0.0-SNAPSHOT > *'
+}
diff --git a/end-to-end/native-i18n/build.gradle b/end-to-end/native-i18n/build.gradle
new file mode 100644
index 00000000000..08521db207e
--- /dev/null
+++ b/end-to-end/native-i18n/build.gradle
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+plugins {
+ id 'org.apache.grails.buildsrc.properties'
+ id 'org.apache.grails.buildsrc.dependency-validator'
+ id 'org.apache.grails.buildsrc.compile'
+ id 'org.apache.grails.buildsrc.vulnerability-scan'
+ id 'org.apache.grails.gradle.grails-web'
+ id 'org.graalvm.buildtools.native' version "$graalvmBuildtoolsVersion" apply false
+}
+
+version = '0.1'
+group = 'nativei18n'
+
+grails {
+ // The Grails Gradle plugin already sets this as a convention for any application that applies
+ // GraalVM's plugin, so the native half would get it anyway. It is set here so the JVM half is
+ // compiled the same way as the image, rather than being a second dialect of the same fixture.
+ indy = true
+}
+
+dependencies {
+ implementation platform("org.apache.grails:grails-bom:$projectVersion")
+ implementation project(':native-i18n-plugin')
+ implementation 'org.apache.grails:grails-dependencies-starter-web'
+}
+
+apply {
+ from rootProject.layout.projectDirectory.file('../gradle/grails-extension-gradle-config.gradle')
+}
+
+// Runs on any JDK, and proves only that the fixture and its assertions are self-consistent - on a
+// JVM every bundle is readable whether it was registered or not. Cheap enough to keep in `check` so
+// the assertions cannot drift from the bundles while the native job is not being run.
+tasks.register('i18nCheckOnJvm', JavaExec) {
+ group = 'verification'
+ description = 'Resolves every message bundle from the packaged application on a JVM'
+ dependsOn tasks.named('bootJar')
+ classpath = files(tasks.named('bootJar').flatMap { it.archiveFile })
+ mainClass = 'org.springframework.boot.loader.launch.JarLauncher'
+ args = ['--i18n-check', '--server.port=0', '--spring.main.banner-mode=off']
+}
+
+tasks.named('check') {
+ dependsOn tasks.named('i18nCheckOnJvm')
+}
+
+// The native half is opt-in: it needs a GraalVM toolchain and several minutes of CPU, which is too
+// much to ask of every run of this build. Enable with -PnativeTests.
+if (project.hasProperty('nativeTests')) {
+ pluginManager.apply('org.graalvm.buildtools.native')
+
+ graalvmNative {
+ binaries {
+ main {
+ imageName = 'native-i18n'
+ mainClass = 'nativei18n.Application'
+ // Measured on a 32GB machine with GraalVM CE 25.2.4: the default 16 threads
+ // exhausted the heap, 4 built in about six minutes.
+ buildArgs.add('--parallelism=4')
+ }
+ }
+ // Build the image with GRAALVM_HOME/JAVA_HOME rather than letting Gradle select a toolchain.
+ // The framework is published on the JDK the repository pins and the image is built on a
+ // GraalVM, so there is no one toolchain that could be detected for both.
+ toolchainDetection = false
+ }
+
+ tasks.register('i18nCheckOnNative', Exec) {
+ group = 'verification'
+ description = 'Resolves every message bundle from a compiled GraalVM binary'
+ // The path comes from the task that produces the binary, so the location and the dependency
+ // on its producer stay in one place rather than repeating the layout convention here.
+ Provider binary = tasks.named('nativeCompile').flatMap { it.outputFile }
+ inputs.file(binary)
+ doFirst {
+ commandLine binary.get().asFile.absolutePath,
+ '--i18n-check', '--server.port=0', '--spring.main.banner-mode=off'
+ }
+ }
+
+ tasks.named('check') {
+ dependsOn tasks.named('i18nCheckOnNative')
+ }
+}
diff --git a/end-to-end/native-i18n/grails-app/conf/application.yml b/end-to-end/native-i18n/grails-app/conf/application.yml
new file mode 100644
index 00000000000..55e2ec9c1c0
--- /dev/null
+++ b/end-to-end/native-i18n/grails-app/conf/application.yml
@@ -0,0 +1,27 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+spring:
+ messages:
+ # Dotted, so the run also proves a base name is converted to a resource path
+ # (config.i18n.custom -> config/i18n/custom.properties) before it is used.
+ basename: config.i18n.custom
+ fallback-to-system-locale: false
+ # Not a base name, so resolving an unknown code to itself proves the rest of
+ # MessageSourceProperties was bound too - they all arrive together or not at all.
+ use-code-as-default-message: true
diff --git a/end-to-end/native-i18n/grails-app/i18n/messages.properties b/end-to-end/native-i18n/grails-app/i18n/messages.properties
new file mode 100644
index 00000000000..baacbb0e21c
--- /dev/null
+++ b/end-to-end/native-i18n/grails-app/i18n/messages.properties
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+native.app.greeting=hello from the application bundle
diff --git a/end-to-end/native-i18n/grails-app/i18n/messages_fr.properties b/end-to-end/native-i18n/grails-app/i18n/messages_fr.properties
new file mode 100644
index 00000000000..6e63f14ef76
--- /dev/null
+++ b/end-to-end/native-i18n/grails-app/i18n/messages_fr.properties
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+native.app.greeting=bonjour depuis le paquet de l'application
diff --git a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
new file mode 100644
index 00000000000..e48445ce215
--- /dev/null
+++ b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package nativei18n
+
+import grails.boot.GrailsApp
+import grails.boot.config.GrailsAutoConfiguration
+
+import org.springframework.context.ConfigurableApplicationContext
+import org.springframework.context.MessageSource
+
+/**
+ * Resolves one message from each way a bundle reaches the message source, and fails if any of them
+ * does not resolve.
+ *
+ * Run on a JVM this proves two things. That every bundle is reachable at all — which is a real
+ * guard, because Spring Boot's message source is configured from {@code MessageSourceProperties},
+ * and a bean created before {@code ConfigurationPropertiesBindingPostProcessor} is registered keeps
+ * its defaults, silently losing every base name except {@code messages}. And, when compiled into a
+ * GraalVM binary, that each bundle was registered as a resource — a failure no JVM run can produce,
+ * because on a JVM every bundle on the classpath is readable whether it was registered or not. A
+ * bundle missing from an image surfaces as a code resolving to itself, not as an exception, because
+ * {@code spring.messages.use-code-as-default-message} is on.
+ *
+ * Only the first of the three is covered by Spring Boot's own hints, which register the two
+ * hardcoded patterns {@code messages.properties} and {@code messages_*.properties} and derive
+ * nothing from the configured base names.
+ */
+class Application extends GrailsAutoConfiguration {
+
+ static void main(String[] args) {
+ if (!args.contains('--i18n-check')) {
+ GrailsApp.run(Application, args)
+ return
+ }
+
+ ConfigurableApplicationContext context = (ConfigurableApplicationContext) GrailsApp.run(Application, args)
+ int exitCode = 0
+ try {
+ MessageSource messages = context.getBean(MessageSource)
+
+ // The application's own bundle, base name 'messages' — the one case Boot's hints cover.
+ check(messages, 'native.app.greeting', Locale.ENGLISH, 'hello from the application bundle')
+
+ // A plugin's bundle, base name 'native-messages'. Namespaced, so Boot's messages*
+ // patterns never reach it; it survives only because the base names are recorded at build
+ // time and hinted from them. The plugin name is also multi-word, so this covers the
+ // descriptor's hyphenated spelling being matched against the plugin's camel-case one.
+ check(messages, 'native.plugin.greeting', Locale.ENGLISH, 'hello from the plugin bundle')
+
+ // A base name the application configured itself, written in dotted form, so this proves
+ // config.i18n.custom was converted to config/i18n/custom before being used.
+ check(messages, 'native.custom.greeting', Locale.ENGLISH, 'hello from a configured base name')
+
+ // A locale variant of each. In an image this is what would fail if the hints registered
+ // bundles instead of resource patterns and the image were built with a narrower locale
+ // set than the bundles cover.
+ check(messages, 'native.app.greeting', Locale.FRENCH, "bonjour depuis le paquet de l'application")
+ check(messages, 'native.plugin.greeting', Locale.FRENCH, 'bonjour depuis le paquet du plugin')
+ check(messages, 'native.custom.greeting', Locale.FRENCH, 'bonjour depuis un nom de base configure')
+
+ // Not a base name, so this proves the rest of MessageSourceProperties was bound too:
+ // the whole object binds at once or not at all.
+ String unknown = messages.getMessage('no.such.code', null, Locale.ENGLISH)
+ if (unknown != 'no.such.code') {
+ throw new IllegalStateException('spring.messages.use-code-as-default-message did not reach ' +
+ "the message source; an unknown code gave '${unknown}'")
+ }
+
+ println 'i18n-check: every message bundle resolved'
+ }
+ catch (Throwable failure) {
+ failure.printStackTrace()
+ exitCode = 1
+ }
+ finally {
+ context.close()
+ }
+ // Exit explicitly rather than letting a throwable leave main, which would make the exit code
+ // wait on every non-daemon thread the application started - more of a risk for the binary
+ // than for the jar.
+ System.exit(exitCode)
+ }
+
+ /**
+ * {@code spring.messages.use-code-as-default-message} is on, so a bundle that never reached the
+ * message source does not raise anything — the code comes back as its own value. That is the
+ * shape a missing resource registration takes in an image, so it is reported as itself rather
+ * than as a plain mismatch.
+ */
+ private static void check(MessageSource messages, String code, Locale locale, String expected) {
+ String actual = messages.getMessage(code, null, locale)
+ if (actual == code) {
+ throw new IllegalStateException("'${code}' did not resolve for ${locale}; it came back as its own " +
+ 'code, so its bundle never reached the message source')
+ }
+ if (actual != expected) {
+ throw new IllegalStateException(
+ "'${code}' for ${locale} resolved to '${actual}', expected '${expected}'")
+ }
+ }
+}
diff --git a/end-to-end/native-i18n/src/main/resources/config/i18n/custom.properties b/end-to-end/native-i18n/src/main/resources/config/i18n/custom.properties
new file mode 100644
index 00000000000..2afac18c2e9
--- /dev/null
+++ b/end-to-end/native-i18n/src/main/resources/config/i18n/custom.properties
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+native.custom.greeting=hello from a configured base name
diff --git a/end-to-end/native-i18n/src/main/resources/config/i18n/custom_fr.properties b/end-to-end/native-i18n/src/main/resources/config/i18n/custom_fr.properties
new file mode 100644
index 00000000000..7dec7d5c43f
--- /dev/null
+++ b/end-to-end/native-i18n/src/main/resources/config/i18n/custom_fr.properties
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+native.custom.greeting=bonjour depuis un nom de base configure
diff --git a/end-to-end/settings.gradle b/end-to-end/settings.gradle
index 428275ad5b9..9cd01e34906 100644
--- a/end-to-end/settings.gradle
+++ b/end-to-end/settings.gradle
@@ -104,6 +104,11 @@ rootProject.name = 'grails-end-to-end'
include(
'legacy-commands',
'legacy-commands-plugin',
+ // Verifies message resolution inside a compiled GraalVM binary. The native half is opt-in
+ // (-PnativeTests) because it needs a GraalVM toolchain and minutes of CPU; without the flag
+ // the module still builds and checks the same assertions on a JVM.
+ 'native-i18n',
+ 'native-i18n-plugin',
// Builds an application twice without a clean, to prove a renamed or deleted tag library
// cannot survive in the index that is published. Incremental behaviour against real
// published artifacts is not something the core build can express.
From e59381a9e2431887eab6de818b5f68761c80c26e Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Tue, 13 Oct 2026 12:14:54 -0700
Subject: [PATCH 02/39] Drop the explicit indy setting from native-i18n
Applying GraalVM's plugin already makes the Grails Gradle plugin default
invokedynamic on, so the native half compiles with it either way. The
JVM half resolves the same bundles whichever way it is compiled.
---
end-to-end/native-i18n/build.gradle | 7 -------
1 file changed, 7 deletions(-)
diff --git a/end-to-end/native-i18n/build.gradle b/end-to-end/native-i18n/build.gradle
index 08521db207e..f70f4d7d838 100644
--- a/end-to-end/native-i18n/build.gradle
+++ b/end-to-end/native-i18n/build.gradle
@@ -29,13 +29,6 @@ plugins {
version = '0.1'
group = 'nativei18n'
-grails {
- // The Grails Gradle plugin already sets this as a convention for any application that applies
- // GraalVM's plugin, so the native half would get it anyway. It is set here so the JVM half is
- // compiled the same way as the image, rather than being a second dialect of the same fixture.
- indy = true
-}
-
dependencies {
implementation platform("org.apache.grails:grails-bom:$projectVersion")
implementation project(':native-i18n-plugin')
From 6e272a0b1f47c232245cdc8a9df9127a7ab03ec1 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Tue, 13 Oct 2026 12:15:43 -0700
Subject: [PATCH 03/39] Declare the GraalVM plugin in the end-to-end root build
Declaring it in native-i18n alone gave that project a plugin classloader
of its own, so its vulnerabilityScan task could not be created: the
shared OsvVulnerabilityService had already been registered from another
project's classloader. Declared once at the root with apply false, every
project shares the same classes and native-i18n still applies the plugin
only under -PnativeTests.
---
end-to-end/build.gradle | 4 ++++
end-to-end/native-i18n/build.gradle | 1 -
2 files changed, 4 insertions(+), 1 deletion(-)
diff --git a/end-to-end/build.gradle b/end-to-end/build.gradle
index 3f49ad3d0aa..ef1bc5e7c1d 100644
--- a/end-to-end/build.gradle
+++ b/end-to-end/build.gradle
@@ -22,6 +22,10 @@ plugins {
// workflow bumps, so the suite always resolves the version the core build just published.
// Every subproject inherits it from here.
id 'org.apache.grails.buildsrc.properties'
+ // Applied only by native-i18n, and only with -PnativeTests. Declared here rather than in that
+ // project, because a plugin only one project declares gives it a classloader of its own, and the
+ // vulnerability scan's shared build service cannot then be handed to its task there.
+ id 'org.graalvm.buildtools.native' version "$graalvmBuildtoolsVersion" apply false
}
def localMavenRepo = rootProject.layout.projectDirectory.dir('../build/local-maven')
diff --git a/end-to-end/native-i18n/build.gradle b/end-to-end/native-i18n/build.gradle
index f70f4d7d838..de971e8aeba 100644
--- a/end-to-end/native-i18n/build.gradle
+++ b/end-to-end/native-i18n/build.gradle
@@ -23,7 +23,6 @@ plugins {
id 'org.apache.grails.buildsrc.compile'
id 'org.apache.grails.buildsrc.vulnerability-scan'
id 'org.apache.grails.gradle.grails-web'
- id 'org.graalvm.buildtools.native' version "$graalvmBuildtoolsVersion" apply false
}
version = '0.1'
From 152d097a941b84673b20b801aeef60778fceab15 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Tue, 13 Oct 2026 12:16:02 -0700
Subject: [PATCH 04/39] Bring the native-i18n README up to date with 9.0.x
9.0.x is on Groovy 6.0.0, which carries the AOT link mode and ships its
own native-image configuration, not 6.0.0-beta-2. Invokedynamic is on
for the library modules only: the plugin modules, including grails-gsp,
grails-sitemesh3 and grails-cache from the web starter, still follow the
Grails Gradle plugin's default until #16165 changes it.
---
end-to-end/README.md | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/end-to-end/README.md b/end-to-end/README.md
index df07f0a7e00..c1c69733770 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -84,7 +84,7 @@ cd end-to-end
The JVM half runs in `check` and needs nothing special. It cannot falsify a hint; its value is as a
fixture guard, keeping the bundles and the assertions from drifting apart. The native half is opt-in
-because it needs a GraalVM toolchain and minutes of CPU, not because it is expected to fail.
+because it needs a GraalVM toolchain and minutes of CPU.
### Why this runs here and not on 8.0.x
@@ -92,8 +92,8 @@ Dynamic Groovy in a native image needs two things this branch has and 8.0.x deli
| | 8.0.x | here |
|---|---|---|
-| `groovy.version` | 5.1.2 | 6.0.0-beta-2, which carries [GROOVY-12234](https://issues.apache.org/jira/browse/GROOVY-12234)'s AOT link mode for indy dispatch |
-| framework invokedynamic | forced off in `CompilePlugin`, because Groovy 5's indy default is a large runtime regression for dynamic Groovy (#15293) | Groovy's default, which is on |
+| Groovy | 5, which has no AOT link mode | 6.0.0, which carries [GROOVY-12234](https://issues.apache.org/jira/browse/GROOVY-12234)'s AOT link mode for indy dispatch and ships its own native-image configuration |
+| framework invokedynamic | off by default in `CompilePlugin`, because Groovy 5's indy default is a large runtime regression for dynamic Groovy (#15293) | on for the library modules, which `CompilePlugin` compiles with it; the plugin modules take the Grails Gradle plugin's `indy` default, which #16165 turns on |
Without the AOT link mode, indy-compiled Groovy cannot link in an image: the runtime invokes
`IndyInterface`'s bootstrap method without its `` having run, so a `static final` handle is
@@ -101,7 +101,9 @@ still null and it fails as `BootstrapMethodError: NullPointerException` at
`IndyInterface.makeBootHandle`. Without invokedynamic at all, Groovy classes carry a `CallSiteArray`
and define call-site classes as they run, which an image forbids: `UnsupportedFeatureError: Tried to
define class`, naming a class nobody wrote. Either one on its own is fatal, which is why native
-image is not a Grails 8 capability and this module is not on that branch.
+image is not a Grails 8 capability and this module is not on that branch. Until #16165 is merged
+the second applies here too: `grails-gsp`, `grails-sitemesh3` and `grails-cache`, which the web
+starter brings in, are published with classic call sites.
### What it needs
From 7457422ee1200fac7779f434eedbe4a2a885098d Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 19:15:03 -0700
Subject: [PATCH 05/39] Drop the README's caveat about #16165
#16165 made invokedynamic the default for the framework's plugin modules
and for applications, so grails-gsp, grails-sitemesh3 and grails-cache are
no longer published with classic call sites.
---
end-to-end/README.md | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/end-to-end/README.md b/end-to-end/README.md
index c1c69733770..b0fc27e1e62 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -93,7 +93,7 @@ Dynamic Groovy in a native image needs two things this branch has and 8.0.x deli
| | 8.0.x | here |
|---|---|---|
| Groovy | 5, which has no AOT link mode | 6.0.0, which carries [GROOVY-12234](https://issues.apache.org/jira/browse/GROOVY-12234)'s AOT link mode for indy dispatch and ships its own native-image configuration |
-| framework invokedynamic | off by default in `CompilePlugin`, because Groovy 5's indy default is a large runtime regression for dynamic Groovy (#15293) | on for the library modules, which `CompilePlugin` compiles with it; the plugin modules take the Grails Gradle plugin's `indy` default, which #16165 turns on |
+| framework invokedynamic | off by default in `CompilePlugin`, because Groovy 5's indy default is a large runtime regression for dynamic Groovy (#15293) | on: Groovy 6's default, which `CompilePlugin` and the Grails Gradle plugin keep unless a build turns it off |
Without the AOT link mode, indy-compiled Groovy cannot link in an image: the runtime invokes
`IndyInterface`'s bootstrap method without its `` having run, so a `static final` handle is
@@ -101,9 +101,7 @@ still null and it fails as `BootstrapMethodError: NullPointerException` at
`IndyInterface.makeBootHandle`. Without invokedynamic at all, Groovy classes carry a `CallSiteArray`
and define call-site classes as they run, which an image forbids: `UnsupportedFeatureError: Tried to
define class`, naming a class nobody wrote. Either one on its own is fatal, which is why native
-image is not a Grails 8 capability and this module is not on that branch. Until #16165 is merged
-the second applies here too: `grails-gsp`, `grails-sitemesh3` and `grails-cache`, which the web
-starter brings in, are published with classic call sites.
+image is not a Grails 8 capability and this module is not on that branch.
### What it needs
From 5e9c52bb77036885a06048f9b2bbdd2bfe4e650a Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 19:24:49 -0700
Subject: [PATCH 06/39] Compile the native-i18n Application class statically
A generated application's Application class is @CompileStatic. This one
was dynamic, so in an image it failed in its own static initializer: the
System.setProperty(BuildSettings.MAIN_CLASS_NAME, ...) statement Grails
injects into every Application class was dispatched through a metaclass
with no reflection metadata for BuildSettings. Compiled statically, the
check depends on resource hints for what it checks and not on reflection
metadata for how it checks it.
---
.../grails-app/init/nativei18n/Application.groovy | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
diff --git a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
index e48445ce215..b23143e59ba 100644
--- a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
+++ b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
@@ -19,6 +19,8 @@
package nativei18n
+import groovy.transform.CompileStatic
+
import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
@@ -41,7 +43,12 @@ import org.springframework.context.MessageSource
* Only the first of the three is covered by Spring Boot's own hints, which register the two
* hardcoded patterns {@code messages.properties} and {@code messages_*.properties} and derive
* nothing from the configured base names.
+ *
+ * Compiled statically, as a generated application's {@code Application} class is, so that the
+ * image depends on resource hints for what this checks and not on reflection metadata for how it
+ * checks it.
*/
+@CompileStatic
class Application extends GrailsAutoConfiguration {
static void main(String[] args) {
@@ -50,7 +57,7 @@ class Application extends GrailsAutoConfiguration {
return
}
- ConfigurableApplicationContext context = (ConfigurableApplicationContext) GrailsApp.run(Application, args)
+ ConfigurableApplicationContext context = GrailsApp.run(Application, args)
int exitCode = 0
try {
MessageSource messages = context.getBean(MessageSource)
From c00fd304283d986a4513c5e1a83caef248be9cff Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:08 -0700
Subject: [PATCH 07/39] Record the main class without dynamic dispatch
Every Application class gets System.setProperty(BuildSettings.MAIN_CLASS_NAME, ...)
in its static initializer. The key was read as a dynamic property, so an
Application class that is not statically compiled failed in a native image
before anything could register reflection metadata for BuildSettings. The key
is now a constant and the call has its target, so it compiles to a direct
invokestatic however the class is compiled.
---
.../injection/ApplicationClassInjector.groovy | 28 ++++++-
.../ApplicationClassInjectorSpec.groovy | 62 ++++++++++++++++
.../injection/StaticInitializerCalls.groovy | 73 +++++++++++++++++++
3 files changed, 159 insertions(+), 4 deletions(-)
create mode 100644 grails-core/src/test/groovy/org/grails/compiler/injection/StaticInitializerCalls.groovy
diff --git a/grails-core/src/main/groovy/org/grails/compiler/injection/ApplicationClassInjector.groovy b/grails-core/src/main/groovy/org/grails/compiler/injection/ApplicationClassInjector.groovy
index bd215309bf4..f243c778728 100644
--- a/grails-core/src/main/groovy/org/grails/compiler/injection/ApplicationClassInjector.groovy
+++ b/grails-core/src/main/groovy/org/grails/compiler/injection/ApplicationClassInjector.groovy
@@ -24,9 +24,11 @@ import org.apache.groovy.ast.tools.AnnotatedNodeUtils
import org.codehaus.groovy.ast.AnnotationNode
import org.codehaus.groovy.ast.ClassHelper
import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.MethodNode
import org.codehaus.groovy.ast.Parameter
import org.codehaus.groovy.ast.expr.ConstantExpression
import org.codehaus.groovy.ast.expr.ListExpression
+import org.codehaus.groovy.ast.expr.MethodCallExpression
import org.codehaus.groovy.ast.stmt.BlockStatement
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.ast.stmt.ReturnStatement
@@ -48,7 +50,6 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.args
import static org.codehaus.groovy.ast.tools.GeneralUtils.callX
import static org.codehaus.groovy.ast.tools.GeneralUtils.classX
import static org.codehaus.groovy.ast.tools.GeneralUtils.constX
-import static org.codehaus.groovy.ast.tools.GeneralUtils.propX
import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt
/**
@@ -116,9 +117,7 @@ class ApplicationClassInjector implements GrailsArtefactClassInjector {
if (!transformedInstances.contains(objectId)) {
transformedInstances << objectId
- List statements = [
- stmt(callX(classX(System), 'setProperty', args(propX(classX(BuildSettings), 'MAIN_CLASS_NAME'), constX(classNode.name))))
- ]
+ List statements = [recordMainClassName(classNode)]
classNode.addStaticInitializerStatements(statements, true)
def packageNamesMethod = classNode.getMethod('packageNames', Parameter.EMPTY_ARRAY)
@@ -173,6 +172,27 @@ class ApplicationClassInjector implements GrailsArtefactClassInjector {
return GrailsResourceUtils.isGrailsResource(res) && res.filename == 'Application.groovy'
}
+ /**
+ * {@code System.setProperty(BuildSettings.MAIN_CLASS_NAME, '')}, written so that
+ * nothing in it is dispatched through a metaclass.
+ *
+ * It runs in the application class's static initializer, which in a native image is before anything
+ * could register reflection metadata for {@link BuildSettings}. An application class that is not
+ * statically compiled would otherwise read the key as a dynamic property and fail there with
+ * {@code MissingPropertyException}. The key is a compile-time constant, so it is inlined, and the call is
+ * given its target, so it is compiled as a direct {@code invokestatic} whichever way the class is
+ * compiled.
+ */
+ private static Statement recordMainClassName(ClassNode classNode) {
+ MethodCallExpression setProperty = callX(classX(System), 'setProperty',
+ args(constX(BuildSettings.MAIN_CLASS_NAME), constX(classNode.name)))
+ Parameter[] keyAndValue = [new Parameter(ClassHelper.STRING_TYPE, 'key'),
+ new Parameter(ClassHelper.STRING_TYPE, 'value')] as Parameter[]
+ MethodNode target = ClassHelper.make(System).getDeclaredMethod('setProperty', keyAndValue)
+ setProperty.methodTarget = target
+ stmt(setProperty)
+ }
+
private static boolean shouldExcludeConditionalAutoConfiguration(Map target) {
def classLoader = ApplicationClassInjector.classLoader
Boolean.parseBoolean(System.getProperty(target.systemProperty, 'true'))
diff --git a/grails-core/src/test/groovy/org/grails/compiler/injection/ApplicationClassInjectorSpec.groovy b/grails-core/src/test/groovy/org/grails/compiler/injection/ApplicationClassInjectorSpec.groovy
index df02a2d5063..f623d761c9f 100644
--- a/grails-core/src/test/groovy/org/grails/compiler/injection/ApplicationClassInjectorSpec.groovy
+++ b/grails-core/src/test/groovy/org/grails/compiler/injection/ApplicationClassInjectorSpec.groovy
@@ -18,13 +18,32 @@
*/
package org.grails.compiler.injection
+import org.codehaus.groovy.control.CompilationUnit
+import org.codehaus.groovy.control.CompilerConfiguration
+
import spock.lang.Specification
+import spock.lang.TempDir
import spock.lang.Unroll
import spock.util.environment.RestoreSystemProperties
+import grails.util.BuildSettings
+
@RestoreSystemProperties
class ApplicationClassInjectorSpec extends Specification {
+ @TempDir
+ File tempDir
+
+ void setup() {
+ // compiling runs the global transformation, which would otherwise pick up trait injectors another
+ // spec left registered
+ TraitInjectionUtils.@traitInjectors = []
+ }
+
+ void cleanup() {
+ TraitInjectionUtils.@traitInjectors = null
+ }
+
@Unroll
def "EXCLUDED_AUTO_CONFIGURE_CLASSES contains expected entry #className"(String className) {
expect:
@@ -97,4 +116,47 @@ class ApplicationClassInjectorSpec extends Specification {
expect:
injector.artefactTypes.contains('Application')
}
+
+ def "a dynamically compiled application class records its name as the main class"() {
+ given: "an application class that is not statically compiled, where a generated project puts it"
+ def targetDir = new File(tempDir, 'build/classes/groovy/main')
+ compile(new File(tempDir, 'grails-app/init/Application.groovy'), '''
+ class Application extends grails.boot.config.GrailsAutoConfiguration {
+ }
+ ''', targetDir)
+ System.clearProperty(BuildSettings.MAIN_CLASS_NAME)
+
+ when: "the class is initialized"
+ def loader = new URLClassLoader([targetDir.toURI().toURL()] as URL[], getClass().classLoader)
+ Class.forName('Application', true, loader)
+
+ then: "its name is recorded"
+ System.getProperty(BuildSettings.MAIN_CLASS_NAME) == 'Application'
+ }
+
+ def "the statement recording the main class is not dispatched through a metaclass"() {
+ given: "an application class that is not statically compiled"
+ def targetDir = new File(tempDir, 'build/classes/groovy/main')
+ compile(new File(tempDir, 'grails-app/init/Application.groovy'), '''
+ class Application extends grails.boot.config.GrailsAutoConfiguration {
+ }
+ ''', targetDir)
+
+ when: "its static initializer is read"
+ def calls = StaticInitializerCalls.of(new File(targetDir, 'Application.class').bytes)
+
+ then: "System.setProperty is called directly"
+ calls.contains('INVOKESTATIC java/lang/System.setProperty')
+
+ and: "nothing is dispatched dynamically, which a native image could not resolve before any metadata is registered"
+ !calls.any { it.startsWith('INVOKEDYNAMIC') }
+ }
+
+ private static void compile(File sourceFile, String source, File targetDirectory) {
+ sourceFile.parentFile.mkdirs()
+ sourceFile.text = source
+ def compilationUnit = new CompilationUnit(new CompilerConfiguration(targetDirectory: targetDirectory))
+ compilationUnit.addSource(sourceFile)
+ compilationUnit.compile()
+ }
}
diff --git a/grails-core/src/test/groovy/org/grails/compiler/injection/StaticInitializerCalls.groovy b/grails-core/src/test/groovy/org/grails/compiler/injection/StaticInitializerCalls.groovy
new file mode 100644
index 00000000000..de05825488e
--- /dev/null
+++ b/grails-core/src/test/groovy/org/grails/compiler/injection/StaticInitializerCalls.groovy
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.compiler.injection
+
+import groovy.transform.CompileStatic
+import groovyjarjarasm.asm.ClassReader
+import groovyjarjarasm.asm.ClassVisitor
+import groovyjarjarasm.asm.Handle
+import groovyjarjarasm.asm.MethodVisitor
+import groovyjarjarasm.asm.Opcodes
+
+/**
+ * The calls a class makes in its static initializer, as {@code INVOKESTATIC owner.name} for a direct
+ * static call and {@code INVOKEDYNAMIC name} for a call dispatched dynamically.
+ *
+ * A native image runs a class's static initializer before anything could register reflection
+ * metadata for what it calls, so a call there that goes through Groovy's dynamic dispatch fails in an
+ * image however the application was traced. Reading the bytecode is the one way to see which kind a
+ * call compiled to.
+ */
+@CompileStatic
+class StaticInitializerCalls {
+
+ static List of(byte[] classFile) {
+ List calls = []
+ new ClassReader(classFile).accept(new ClassVisitor(Opcodes.ASM9) {
+ @Override
+ MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
+ if (name != '') {
+ return null
+ }
+ new MethodVisitor(Opcodes.ASM9) {
+ @Override
+ void visitMethodInsn(int opcode, String owner, String methodName, String methodDescriptor, boolean isInterface) {
+ calls << "${opcode == Opcodes.INVOKESTATIC ? 'INVOKESTATIC' : 'INVOKE'} ${owner}.${methodName}".toString()
+ }
+
+ @Override
+ void visitInvokeDynamicInsn(String methodName, String methodDescriptor, Handle bootstrap, Object... bootstrapArguments) {
+ calls << "INVOKEDYNAMIC ${methodName}".toString()
+ }
+ }
+ }
+ }, 0)
+ calls
+ }
+
+ static List of(Class> type) {
+ InputStream input = type.getResourceAsStream('/' + type.name.replace('.', '/') + '.class')
+ try {
+ return of(input.bytes)
+ }
+ finally {
+ input.close()
+ }
+ }
+}
From 0e924837cd1b03ae8c672311572b81fd595b6176 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:08 -0700
Subject: [PATCH 08/39] Compile the Settings interface statically
Its one computed constant, DEFAULT_ENCODING, called System.getProperty through
a metaclass as the interface was initialized, which a native image cannot do
for a JDK method nothing registered.
---
.../main/groovy/grails/config/Settings.groovy | 8 ++++
.../groovy/grails/config/SettingsSpec.groovy | 45 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 grails-core/src/test/groovy/grails/config/SettingsSpec.groovy
diff --git a/grails-core/src/main/groovy/grails/config/Settings.groovy b/grails-core/src/main/groovy/grails/config/Settings.groovy
index 1ae9d523d31..d8ededfe856 100644
--- a/grails-core/src/main/groovy/grails/config/Settings.groovy
+++ b/grails-core/src/main/groovy/grails/config/Settings.groovy
@@ -19,12 +19,20 @@
package grails.config
+import groovy.transform.CompileStatic
+
/**
* Constants for names of settings in Grails
*
+ * Compiled statically, because one constant is computed rather than written out and the interface
+ * is initialized as an application starts: compiled dynamically, its {@code System.getProperty} call
+ * was dispatched through a metaclass, which a native image cannot do for a JDK method nothing
+ * registered.
+ *
* @author Graeme Rocher
* @since 3.0
*/
+@CompileStatic
interface Settings {
/**
diff --git a/grails-core/src/test/groovy/grails/config/SettingsSpec.groovy b/grails-core/src/test/groovy/grails/config/SettingsSpec.groovy
new file mode 100644
index 00000000000..cac57cbaefe
--- /dev/null
+++ b/grails-core/src/test/groovy/grails/config/SettingsSpec.groovy
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package grails.config
+
+import spock.lang.Specification
+
+import org.grails.compiler.injection.StaticInitializerCalls
+
+/**
+ * Covers the one computed constant in {@link Settings}, which is evaluated as an application starts.
+ */
+class SettingsSpec extends Specification {
+
+ void 'the default encoding is the platform file encoding'() {
+ expect:
+ Settings.DEFAULT_ENCODING == System.getProperty('file.encoding', 'UTF-8')
+ }
+
+ void 'the default encoding is read without dynamic dispatch'() {
+ when:
+ def calls = StaticInitializerCalls.of(Settings)
+
+ then: 'System.getProperty is called directly'
+ calls.contains('INVOKESTATIC java/lang/System.getProperty')
+
+ and: 'nothing goes through a metaclass, which a native image cannot do for a JDK method nothing registered'
+ !calls.any { it.startsWith('INVOKEDYNAMIC') }
+ }
+}
From 74932d61b43121b7e8000202c3aec3f413a5f073 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:08 -0700
Subject: [PATCH 09/39] Compile MultiTenancySettings statically
Each multi tenancy mode was built with a map created by a dynamic new, so
every mapping context failed to initialize the enum in a native image.
---
.../multitenancy/MultiTenancySettings.groovy | 2 +
.../MultiTenancySettingsSpec.groovy | 99 +++++++++++++++++++
2 files changed, 101 insertions(+)
create mode 100644 grails-datastore-core/src/test/groovy/org/grails/datastore/mapping/multitenancy/MultiTenancySettingsSpec.groovy
diff --git a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/multitenancy/MultiTenancySettings.groovy b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/multitenancy/MultiTenancySettings.groovy
index c02995ab61a..faf48bade87 100644
--- a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/multitenancy/MultiTenancySettings.groovy
+++ b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/multitenancy/MultiTenancySettings.groovy
@@ -19,6 +19,7 @@
package org.grails.datastore.mapping.multitenancy
+import groovy.transform.CompileStatic
import groovy.transform.builder.Builder
import groovy.transform.builder.SimpleStrategy
@@ -30,6 +31,7 @@ import org.grails.datastore.mapping.multitenancy.resolvers.NoTenantResolver
/**
* Represents the multi tenancy settings
*/
+@CompileStatic
@Builder(builderStrategy = SimpleStrategy, prefix = '')
class MultiTenancySettings {
diff --git a/grails-datastore-core/src/test/groovy/org/grails/datastore/mapping/multitenancy/MultiTenancySettingsSpec.groovy b/grails-datastore-core/src/test/groovy/org/grails/datastore/mapping/multitenancy/MultiTenancySettingsSpec.groovy
new file mode 100644
index 00000000000..7065294085d
--- /dev/null
+++ b/grails-datastore-core/src/test/groovy/org/grails/datastore/mapping/multitenancy/MultiTenancySettingsSpec.groovy
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.datastore.mapping.multitenancy
+
+import groovyjarjarasm.asm.ClassReader
+import groovyjarjarasm.asm.ClassVisitor
+import groovyjarjarasm.asm.Handle
+import groovyjarjarasm.asm.MethodVisitor
+import groovyjarjarasm.asm.Opcodes
+
+import spock.lang.Specification
+
+import org.grails.datastore.mapping.core.connections.ConnectionSource
+import org.grails.datastore.mapping.multitenancy.MultiTenancySettings.MultiTenancyMode
+import org.grails.datastore.mapping.multitenancy.resolvers.NoTenantResolver
+
+/**
+ * Covers the multi tenancy settings every mapping context reads as it is created.
+ */
+class MultiTenancySettingsSpec extends Specification {
+
+ void 'settings with nothing configured mean no multi tenancy'() {
+ when:
+ def settings = new MultiTenancySettings()
+
+ then:
+ settings.mode == MultiTenancyMode.NONE
+ settings.tenantResolver instanceof NoTenantResolver
+ }
+
+ void 'a configured resolver class is created when the resolver is asked for'() {
+ when:
+ def settings = new MultiTenancySettings().tenantResolverClass(NoTenantResolver)
+
+ then:
+ settings.tenantResolver instanceof NoTenantResolver
+ }
+
+ void 'a mode sharing a connection resolves every tenant to the default connection'() {
+ expect:
+ MultiTenancySettings.resolveConnectionForTenantId(mode, 'tenant') == connection
+
+ where:
+ mode || connection
+ MultiTenancyMode.DATABASE || 'tenant'
+ MultiTenancyMode.SCHEMA || ConnectionSource.DEFAULT
+ MultiTenancyMode.DISCRIMINATOR || ConnectionSource.DEFAULT
+ }
+
+ void 'the modes are created without dynamic dispatch'() {
+ when: 'what runs while the mode enum is initialized is read: its static initializer and the constructors it calls'
+ def dynamicCalls = dynamicCallsWhileInitializing(MultiTenancyMode)
+
+ then: 'every mapping context reads the mode as it is created, and a native image cannot resolve a ' +
+ 'dynamic call for a JDK class nothing registered -- it failed creating the map each constant is built with'
+ !dynamicCalls.contains('init')
+ }
+
+ private static List dynamicCallsWhileInitializing(Class> type) {
+ List calls = []
+ InputStream input = type.getResourceAsStream('/' + type.name.replace('.', '/') + '.class')
+ try {
+ new ClassReader(input.bytes).accept(new ClassVisitor(Opcodes.ASM9) {
+ @Override
+ MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
+ if (name != '' && name != '') {
+ return null
+ }
+ new MethodVisitor(Opcodes.ASM9) {
+ @Override
+ void visitInvokeDynamicInsn(String methodName, String methodDescriptor, Handle bootstrap, Object... bootstrapArguments) {
+ calls << methodName
+ }
+ }
+ }
+ }, 0)
+ }
+ finally {
+ input.close()
+ }
+ calls
+ }
+}
From 5172bc8bfc6d27b8bff75bb9b10f8f152a85b350 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:08 -0700
Subject: [PATCH 10/39] Create the default stack trace filterer directly
Creating it reflectively needed its constructor registered in a native image,
where every application logged that it fell back to the very class it asked
for. A configured subclass is still created as configured.
---
.../core/GrailsBootstrapRegistryInitializer.java | 7 ++++++-
...GrailsBootstrapRegistryInitializerSpec.groovy | 16 ++++++++++++++++
2 files changed, 22 insertions(+), 1 deletion(-)
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/GrailsBootstrapRegistryInitializer.java b/grails-core/src/main/groovy/org/apache/grails/core/GrailsBootstrapRegistryInitializer.java
index 51ff99d22e0..f95fd229481 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/GrailsBootstrapRegistryInitializer.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/GrailsBootstrapRegistryInitializer.java
@@ -123,7 +123,12 @@ private StackTraceFilterer resolveConfiguredStackTraceFilterer(ConfigurableAppli
StackTraceFilterer filterer;
try {
- filterer = BeanUtils.instantiateClass(filtererClass, StackTraceFilterer.class);
+ // The default is created directly: reflection would need its constructor registered in a
+ // native image, where every application would otherwise log that it fell back to the very
+ // class it asked for.
+ filterer = (filtererClass == DefaultStackTraceFilterer.class) ?
+ new DefaultStackTraceFilterer() :
+ BeanUtils.instantiateClass(filtererClass, StackTraceFilterer.class);
}
catch (Throwable t) {
LOG.warn("Problem instantiating configured StackTraceFilterer [{}], falling back to default: {}",
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/GrailsBootstrapRegistryInitializerSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/GrailsBootstrapRegistryInitializerSpec.groovy
index 405dfbb0975..6e09ef3b45a 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/GrailsBootstrapRegistryInitializerSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/GrailsBootstrapRegistryInitializerSpec.groovy
@@ -65,6 +65,19 @@ class GrailsBootstrapRegistryInitializerSpec extends Specification {
promotedFilterer(context) instanceof DefaultStackTraceFilterer
}
+ def 'promotes a configured subclass of the default rather than the default itself'() {
+ given: 'the default is created directly, so a subclass must not be mistaken for it'
+ def context = contextWithProperties([
+ (Settings.SETTING_LOGGING_STACKTRACE_FILTER_CLASS): ExtendedDefaultStackTraceFilterer.name
+ ])
+
+ when:
+ closeBootstrapContext(context)
+
+ then:
+ promotedFilterer(context).class == ExtendedDefaultStackTraceFilterer
+ }
+
def 'promotes the class configured via grails.logging.stackTraceFiltererClass as a class name'() {
given: 'the string form, as written in application.yml or application.properties'
def context = contextWithProperties([
@@ -283,6 +296,9 @@ class GrailsBootstrapRegistryInitializerSpec extends Specification {
exception
}
+ static class ExtendedDefaultStackTraceFilterer extends DefaultStackTraceFilterer {
+ }
+
static class RecordingStackTraceFilterer implements StackTraceFilterer {
int recursiveCalls = 0
From d87e8301bef740b23184d45ae3fb669658509c23 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:08 -0700
Subject: [PATCH 11/39] Carry the build information into a native image
META-INF/grails.build.info says which environment the application was packaged
for. Without it an image started in the development environment.
---
.../grails/core/aot/GrailsResourceRuntimeHints.java | 10 ++++++++++
.../core/aot/GrailsResourceRuntimeHintsSpec.groovy | 6 ++++++
2 files changed, 16 insertions(+)
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsResourceRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsResourceRuntimeHints.java
index 07c8fae1747..79a86d7e7b3 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsResourceRuntimeHints.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsResourceRuntimeHints.java
@@ -70,8 +70,18 @@ public class GrailsResourceRuntimeHints implements RuntimeHintsRegistrar {
*/
public static final String ADDITIONAL_PATTERNS_PROPERTY = "grails.aot.resource-patterns";
+ /**
+ * What the build writes into the application about itself, read by name while the environment is
+ * prepared: the environment it was packaged for, the identity type GORM gives a domain class that
+ * declares none, and the application's name, version and Grails version. An image built without it
+ * starts in the development environment. Written out rather than taken from {@code Metadata},
+ * whose constant is a Groovy property and so not visible here.
+ */
+ private static final String BUILD_INFO = "META-INF/grails.build.info";
+
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ hints.resources().registerPattern(BUILD_INFO);
for (String pattern : ASSETS) {
hints.resources().registerPattern(pattern);
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsResourceRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsResourceRuntimeHintsSpec.groovy
index ca806e40ae3..d930807a777 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsResourceRuntimeHintsSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsResourceRuntimeHintsSpec.groovy
@@ -50,6 +50,12 @@ class GrailsResourceRuntimeHintsSpec extends Specification {
.collect { it.pattern } as Set
}
+ void 'what the build writes about the application is registered'() {
+ expect: 'it says which environment the application was packaged for, so an image without it ' +
+ 'starts in development'
+ 'META-INF/grails.build.info' in registeredPatterns()
+ }
+
void 'the compiled assets are registered'() {
expect: 'asset-pipeline serves them from the classpath by the path that was asked for'
registeredPatterns().containsAll(['assets/*', 'assets/**'])
From 743521be4e59731b2f0d1eaf413845d64d3bd9af Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:08 -0700
Subject: [PATCH 12/39] Register the default validation messages as a bundle
ConstrainedProperty loads them with ResourceBundle.getBundle as it is
initialized. Without the bundle the URL mappings failed to initialize in a
native image, so the web server never started.
---
.../aot/ConstrainedPropertyRuntimeHints.java | 12 ++++++++++++
.../aot/ConstrainedPropertyRuntimeHintsSpec.groovy | 7 +++++++
2 files changed, 19 insertions(+)
diff --git a/grails-datamapping-validation/src/main/groovy/org/apache/grails/datamapping/validation/aot/ConstrainedPropertyRuntimeHints.java b/grails-datamapping-validation/src/main/groovy/org/apache/grails/datamapping/validation/aot/ConstrainedPropertyRuntimeHints.java
index f71c7934bbc..88f3e559adb 100644
--- a/grails-datamapping-validation/src/main/groovy/org/apache/grails/datamapping/validation/aot/ConstrainedPropertyRuntimeHints.java
+++ b/grails-datamapping-validation/src/main/groovy/org/apache/grails/datamapping/validation/aot/ConstrainedPropertyRuntimeHints.java
@@ -48,6 +48,11 @@
* database. Which of the two an image was traced against is not a property anyone would think to
* keep constant.
*
+ * The default error messages are registered too. {@code ConstrainedProperty} loads them with
+ * {@code ResourceBundle.getBundle} as it is initialized, and an image answers that only for a bundle
+ * it was asked to keep: without it the first class to touch a constraint fails to initialize, which
+ * in a web application is the URL mappings, so the server never starts.
+ *
* @since 8.0
*/
public class ConstrainedPropertyRuntimeHints implements RuntimeHintsRegistrar {
@@ -62,6 +67,12 @@ public class ConstrainedPropertyRuntimeHints implements RuntimeHintsRegistrar {
"org.grails.datastore.gorm.validation.constraints.builder.ConstrainedPropertyBuilder"
};
+ /**
+ * The bundle {@code ConstrainedProperty.MESSAGE_BUNDLE} is loaded from. Written out rather than read
+ * from that interface, whose initialization is what loads it.
+ */
+ private static final String DEFAULT_ERROR_MESSAGES = "grails.gorm.validation.DefaultErrorMessages";
+
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
for (String type : CONSTRAINED_TYPES) {
@@ -70,6 +81,7 @@ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader)
MemberCategory.INVOKE_PUBLIC_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
+ hints.resources().registerResourceBundle(DEFAULT_ERROR_MESSAGES);
}
}
diff --git a/grails-datamapping-validation/src/test/groovy/org/apache/grails/datamapping/validation/aot/ConstrainedPropertyRuntimeHintsSpec.groovy b/grails-datamapping-validation/src/test/groovy/org/apache/grails/datamapping/validation/aot/ConstrainedPropertyRuntimeHintsSpec.groovy
index be3f357e5e4..7ea1f6f955b 100644
--- a/grails-datamapping-validation/src/test/groovy/org/apache/grails/datamapping/validation/aot/ConstrainedPropertyRuntimeHintsSpec.groovy
+++ b/grails-datamapping-validation/src/test/groovy/org/apache/grails/datamapping/validation/aot/ConstrainedPropertyRuntimeHintsSpec.groovy
@@ -23,6 +23,7 @@ import grails.gorm.validation.DefaultConstrainedProperty
import org.springframework.aot.hint.MemberCategory
import org.springframework.aot.hint.RuntimeHints
import org.springframework.aot.hint.TypeReference
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
import spock.lang.Specification
@@ -62,6 +63,12 @@ class ConstrainedPropertyRuntimeHintsSpec extends Specification {
.memberCategories.contains(MemberCategory.INVOKE_DECLARED_METHODS)
}
+ void 'the default error messages are registered as a bundle'() {
+ expect: 'ConstrainedProperty loads them with ResourceBundle.getBundle as it is initialized, which ' +
+ 'an image answers only for a bundle it was asked to keep'
+ RuntimeHintsPredicates.resource().forBundle('grails.gorm.validation.DefaultErrorMessages').test(hints)
+ }
+
void 'the builder that applies them is registered'() {
expect:
registered(org.grails.datastore.gorm.validation.constraints.builder.ConstrainedPropertyBuilder)
From e309277e9380716be770678e7b284f9a6924b01d Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:09 -0700
Subject: [PATCH 13/39] Register the plugin descriptors and the plugins they
name
Plugins are found by reading META-INF/grails-plugin.xml, creating each class it
names and reading its getters, and are located by their class files. A native
image carried none of that, so no plugin was found.
---
.../core/aot/GrailsPluginRuntimeHints.java | 76 +++++++++++++
.../resources/META-INF/spring/aot.factories | 1 +
.../aot/GrailsPluginRuntimeHintsSpec.groovy | 107 ++++++++++++++++++
3 files changed, 184 insertions(+)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsPluginRuntimeHints.java
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsPluginRuntimeHintsSpec.groovy
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsPluginRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsPluginRuntimeHints.java
new file mode 100644
index 00000000000..a693b42fb38
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsPluginRuntimeHints.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+import org.springframework.util.ClassUtils;
+
+import org.apache.grails.common.aot.RegistrableTypes;
+import org.apache.grails.core.plugins.PluginDescriptor;
+import org.apache.grails.core.plugins.PluginUtils;
+
+/**
+ * Registers what finding the plugins reads: the descriptors that list them, and the classes they name.
+ *
+ * Plugins are found by reading every {@code META-INF/grails-plugin.xml} on the classpath, loading
+ * the plugin classes each one names, creating an instance of each and reading its version, the
+ * Grails versions it supports and what it loads after through its getters. An image carries none of
+ * that unless asked: without the descriptors no plugin is found and the application fails to start
+ * with "Grails was unable to load plugins dynamically", and without the classes every plugin fails
+ * to load and the same thing happens. A descriptor is Groovy written largely without static
+ * compilation, so its closures reach its own fields and methods dynamically too -- reading a
+ * constant it declares stopped the context from starting.
+ *
+ * Each plugin class's own class file is registered as a resource as well. A plugin is located by
+ * looking its class file up -- where it was found is the root its other resources are read relative
+ * to -- and an image carries no class files unless asked, so every plugin failed to register with
+ * "Root classpath resource not found".
+ *
+ * The classes are read from the descriptors while the hints are written, on an ordinary JVM with
+ * the full classpath, so a plugin in any package is covered -- an application's own plugins are not
+ * the framework's and are named in no list here.
+ *
+ * @since 9.0
+ */
+public class GrailsPluginRuntimeHints implements RuntimeHintsRegistrar {
+
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ hints.resources().registerPattern(PluginUtils.PLUGIN_XML_PATTERN);
+ ClassLoader loader = (classLoader != null) ? classLoader : ClassUtils.getDefaultClassLoader();
+ for (PluginDescriptor descriptor : PluginUtils.scanPluginDescriptorResources(loader)) {
+ for (String pluginClass : descriptor.getProvidedPlugins()) {
+ if (RegistrableTypes.loads(pluginClass, loader)) {
+ hints.reflection().registerTypeIfPresent(loader, pluginClass,
+ MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
+ MemberCategory.INVOKE_PUBLIC_METHODS,
+ MemberCategory.INVOKE_DECLARED_METHODS,
+ MemberCategory.ACCESS_DECLARED_FIELDS);
+ hints.resources().registerPattern(ClassUtils.convertClassNameToResourcePath(pluginClass) +
+ ClassUtils.CLASS_FILE_SUFFIX);
+ }
+ }
+ }
+ }
+
+}
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index ae59b173c50..e460c5a862b 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -6,6 +6,7 @@ org.apache.grails.core.aot.BeanRegistrarRuntimeHints,\
org.apache.grails.core.aot.GrailsApiRuntimeHints,\
org.apache.grails.core.aot.GrailsBannerRuntimeHints,\
org.apache.grails.core.aot.GrailsClosureRuntimeHints,\
+org.apache.grails.core.aot.GrailsPluginRuntimeHints,\
org.apache.grails.core.aot.GrailsResourceRuntimeHints,\
org.apache.grails.core.aot.GroovyExtensionModuleRuntimeHints
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsPluginRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsPluginRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..5f427e24ec2
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsPluginRuntimeHintsSpec.groovy
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import spock.lang.Specification
+import spock.lang.TempDir
+
+import org.grails.plugins.CoreGrailsPlugin
+
+/**
+ * Covers the plugins being found in an image.
+ *
+ * Plugins are found by reading every {@code META-INF/grails-plugin.xml} on the classpath and
+ * creating an instance of each class it names. An image carries neither unless asked, so an image
+ * built without these hints found no plugin at all and stopped with "Grails was unable to load
+ * plugins dynamically".
+ */
+class GrailsPluginRuntimeHintsSpec extends Specification {
+
+ @TempDir
+ File classpathRoot
+
+ RuntimeHints hints = new RuntimeHints()
+
+ private ClassLoader withDescriptor(String pluginClass) {
+ def descriptor = new File(classpathRoot, 'META-INF/grails-plugin.xml')
+ descriptor.parentFile.mkdirs()
+ descriptor.text = "${pluginClass}"
+ new URLClassLoader([classpathRoot.toURI().toURL()] as URL[], getClass().classLoader)
+ }
+
+ void 'the descriptors that list the plugins are carried'() {
+ when:
+ new GrailsPluginRuntimeHints().registerHints(hints, getClass().classLoader)
+
+ then: 'without them no plugin is found and the application does not start'
+ RuntimeHintsPredicates.resource().forResource('META-INF/grails-plugin.xml').test(hints)
+ }
+
+ void 'a plugin class a descriptor names can be created and read'() {
+ given: 'a descriptor naming a plugin'
+ def loader = withDescriptor(CoreGrailsPlugin.name)
+
+ when:
+ new GrailsPluginRuntimeHints().registerHints(hints, loader)
+
+ then: 'finding it creates an instance and reads its version and the Grails versions it supports through getters'
+ RuntimeHintsPredicates.reflection().onType(CoreGrailsPlugin)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS)
+ .test(hints)
+ }
+
+ void 'the fields and methods of a descriptor can be reached from its closures'() {
+ given: 'a descriptor naming a plugin'
+ def loader = withDescriptor(CoreGrailsPlugin.name)
+
+ when:
+ new GrailsPluginRuntimeHints().registerHints(hints, loader)
+
+ then: 'a closure in the descriptor reads its constants and calls its methods dynamically'
+ RuntimeHintsPredicates.reflection().onType(CoreGrailsPlugin)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.ACCESS_DECLARED_FIELDS)
+ .test(hints)
+ }
+
+ void 'a plugin class a descriptor names can be located'() {
+ given: 'a descriptor naming a plugin'
+ def loader = withDescriptor(CoreGrailsPlugin.name)
+
+ when:
+ new GrailsPluginRuntimeHints().registerHints(hints, loader)
+
+ then: 'a plugin is located by looking its class file up, which an image carries only when asked'
+ RuntimeHintsPredicates.resource().forResource('org/grails/plugins/CoreGrailsPlugin.class').test(hints)
+ }
+
+ void 'a plugin class that cannot be loaded is skipped'() {
+ given: 'a descriptor naming a plugin that is not on the classpath'
+ def loader = withDescriptor('com.example.AbsentGrailsPlugin')
+
+ when:
+ new GrailsPluginRuntimeHints().registerHints(hints, loader)
+
+ then: 'registering it would fail the image build, which parses what it is asked to keep'
+ hints.reflection().typeHints().noneMatch { it.type.name == 'com.example.AbsentGrailsPlugin' }
+ !RuntimeHintsPredicates.resource().forResource('com/example/AbsentGrailsPlugin.class').test(hints)
+ }
+}
From 3ec480857a1eaf697a1bc53b8aa6dcbf4729133f Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:09 -0700
Subject: [PATCH 14/39] Register the classes grails.factories names
The artefact handlers and every other factory are created from their names in
META-INF/grails.factories, through their constructors.
---
.../core/aot/GrailsFactoriesRuntimeHints.java | 109 ++++++++++++++++++
.../resources/META-INF/spring/aot.factories | 1 +
.../GrailsFactoriesRuntimeHintsSpec.groovy | 104 +++++++++++++++++
3 files changed, 214 insertions(+)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsFactoriesRuntimeHints.java
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsFactoriesRuntimeHintsSpec.groovy
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsFactoriesRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsFactoriesRuntimeHints.java
new file mode 100644
index 00000000000..c77dcd5047c
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsFactoriesRuntimeHints.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Enumeration;
+import java.util.LinkedHashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+import org.springframework.util.ClassUtils;
+import org.springframework.util.StringUtils;
+
+import org.apache.grails.common.aot.RegistrableTypes;
+
+/**
+ * Registers the classes named in {@code META-INF/grails.factories}, which the framework creates by name.
+ *
+ * The artefact handlers, and every other factory a module declares there, are found by reading the
+ * file and created reflectively through their constructors. An image keeps a constructor only when
+ * something asked for it, so an image built without these failed while the application was being
+ * initialized, with {@code NoSuchMethodException} naming the first artefact handler's constructor.
+ *
+ * The files are read while the hints are written, on an ordinary JVM with the full classpath, so every
+ * module's declarations are covered, including a plugin's from outside the framework. A class that cannot
+ * be loaded here is skipped, because registering it would fail the image build.
+ *
+ * @since 9.0
+ */
+public class GrailsFactoriesRuntimeHints implements RuntimeHintsRegistrar {
+
+ private static final Log logger = LogFactory.getLog(GrailsFactoriesRuntimeHints.class);
+
+ /**
+ * Where the factories are declared. Written out rather than taken from {@code FactoriesLoaderSupport},
+ * whose constant is a Groovy property and so not visible here.
+ */
+ private static final String FACTORIES = "META-INF/grails.factories";
+
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ hints.resources().registerPattern(FACTORIES);
+ ClassLoader loader = (classLoader != null) ? classLoader : ClassUtils.getDefaultClassLoader();
+ for (String factory : declaredFactories(loader)) {
+ if (RegistrableTypes.loads(factory, loader)) {
+ hints.reflection().registerTypeIfPresent(loader, factory, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
+ }
+ }
+ }
+
+ /** Every class any {@code grails.factories} on the classpath names, whatever it is declared as. */
+ private static Set declaredFactories(@Nullable ClassLoader loader) {
+ Set factories = new LinkedHashSet<>();
+ Enumeration resources;
+ try {
+ resources = (loader != null) ? loader.getResources(FACTORIES) : ClassLoader.getSystemResources(FACTORIES);
+ }
+ catch (IOException ex) {
+ logger.warn("Unable to find " + FACTORIES + " on the classpath", ex);
+ return factories;
+ }
+ while (resources.hasMoreElements()) {
+ URL resource = resources.nextElement();
+ Properties properties = new Properties();
+ try (InputStream input = resource.openStream()) {
+ properties.load(input);
+ }
+ catch (IOException | IllegalArgumentException ex) {
+ logger.warn("Unable to read " + resource, ex);
+ continue;
+ }
+ for (String factoryType : properties.stringPropertyNames()) {
+ for (String name : StringUtils.commaDelimitedListToStringArray(properties.getProperty(factoryType))) {
+ String trimmed = name.trim();
+ if (!trimmed.isEmpty()) {
+ factories.add(trimmed);
+ }
+ }
+ }
+ }
+ return factories;
+ }
+
+}
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index e460c5a862b..19b9c44e2cd 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -6,6 +6,7 @@ org.apache.grails.core.aot.BeanRegistrarRuntimeHints,\
org.apache.grails.core.aot.GrailsApiRuntimeHints,\
org.apache.grails.core.aot.GrailsBannerRuntimeHints,\
org.apache.grails.core.aot.GrailsClosureRuntimeHints,\
+org.apache.grails.core.aot.GrailsFactoriesRuntimeHints,\
org.apache.grails.core.aot.GrailsPluginRuntimeHints,\
org.apache.grails.core.aot.GrailsResourceRuntimeHints,\
org.apache.grails.core.aot.GroovyExtensionModuleRuntimeHints
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsFactoriesRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsFactoriesRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..4ec910f02bf
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsFactoriesRuntimeHintsSpec.groovy
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import spock.lang.Specification
+import spock.lang.TempDir
+
+import org.grails.core.artefact.DomainClassArtefactHandler
+import org.grails.core.artefact.ServiceArtefactHandler
+
+/**
+ * Covers the classes named in {@code META-INF/grails.factories} being creatable in an image.
+ *
+ * The framework reads the file and creates what it names through constructors, so an image built
+ * without these stopped while the application was initialized, unable to create the first artefact
+ * handler.
+ */
+class GrailsFactoriesRuntimeHintsSpec extends Specification {
+
+ @TempDir
+ File classpathRoot
+
+ RuntimeHints hints = new RuntimeHints()
+
+ private ClassLoader withFactories(String declarations) {
+ def factories = new File(classpathRoot, 'META-INF/grails.factories')
+ factories.parentFile.mkdirs()
+ factories.text = declarations
+ new URLClassLoader([classpathRoot.toURI().toURL()] as URL[], getClass().classLoader)
+ }
+
+ private boolean creatable(Class> type) {
+ RuntimeHintsPredicates.reflection().onType(type)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+
+ void 'where the factories are declared is carried'() {
+ when:
+ new GrailsFactoriesRuntimeHints().registerHints(hints, getClass().classLoader)
+
+ then: 'it is read by name at run time'
+ RuntimeHintsPredicates.resource().forResource('META-INF/grails.factories').test(hints)
+ }
+
+ void 'the artefact handlers the framework declares can be created'() {
+ when:
+ new GrailsFactoriesRuntimeHints().registerHints(hints, getClass().classLoader)
+
+ then: 'the one an image failed on first, and the others declared beside it'
+ creatable(DomainClassArtefactHandler)
+ creatable(ServiceArtefactHandler)
+ }
+
+ void 'every class a declaration lists is covered, however it is written'() {
+ given: 'two factories nothing else declares, listed across lines with spaces around the comma'
+ def loader = withFactories(
+ "example.Factory=${FirstFactoryFixture.name} ,\\\n ${SecondFactoryFixture.name}")
+
+ when:
+ new GrailsFactoriesRuntimeHints().registerHints(hints, loader)
+
+ then:
+ creatable(FirstFactoryFixture)
+ creatable(SecondFactoryFixture)
+ }
+
+ void 'a class that cannot be loaded is skipped'() {
+ given:
+ def loader = withFactories('grails.core.ArtefactHandler=com.example.AbsentArtefactHandler')
+
+ when:
+ new GrailsFactoriesRuntimeHints().registerHints(hints, loader)
+
+ then: 'registering it would fail the image build, which parses what it is asked to keep'
+ hints.reflection().typeHints().noneMatch { it.type.name == 'com.example.AbsentArtefactHandler' }
+ }
+}
+
+/** A factory no real declaration names, so finding it proves the declaration in the test was read. */
+class FirstFactoryFixture {
+}
+
+/** The second entry of the same declaration. */
+class SecondFactoryFixture {
+}
From 9d564f7debba03745b82f9d4b3a96ad3a43517b6 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:56:09 -0700
Subject: [PATCH 15/39] Register the Caffeine classes the framework's caches
use
GraalVM's metadata for Caffeine registers the entry class of a size-bounded
cache only once a cache recording statistics is reached, and the framework's
caches record none, so the URL mappings could not be created in a native image.
---
.../grails/core/aot/CaffeineRuntimeHints.java | 71 +++++++++++++++
.../resources/META-INF/spring/aot.factories | 1 +
.../core/aot/CaffeineRuntimeHintsSpec.groovy | 86 +++++++++++++++++++
3 files changed, 158 insertions(+)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/CaffeineRuntimeHints.java
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/CaffeineRuntimeHintsSpec.groovy
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/CaffeineRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/CaffeineRuntimeHints.java
new file mode 100644
index 00000000000..540532d6d1f
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/CaffeineRuntimeHints.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+
+/**
+ * Registers the Caffeine classes the framework's own caches are built from.
+ *
+ * Caffeine generates a class for every combination of the options a cache can be built with, and loads
+ * the one a builder asks for by name: a cache class, and the class of the entries it holds. An image keeps
+ * one only when something asked for it. The metadata GraalVM publishes for Caffeine registers the entry
+ * class of a size-bounded cache only once a cache that also records statistics has been reached, and the
+ * framework's caches do not record them, so an image built without these could not create the URL
+ * mappings, failing with "Cannot reflectively invoke constructor 'PSMS()'".
+ *
+ * Named rather than derived, because the names are Caffeine's and follow from the options the framework
+ * uses, which are few: a bound on the number of entries (most caches), a bound on their total weight (the
+ * URL mappings and the URL creators), weak keys (the codecs' metadata), and a bound on the number of
+ * entries with a removal listener (a datastore session's pending inserts, updates and deletes).
+ *
+ * @since 9.0
+ */
+public class CaffeineRuntimeHints implements RuntimeHintsRegistrar {
+
+ private static final String PACKAGE = "com.github.benmanes.caffeine.cache.";
+
+ /**
+ * The classes the framework's caches are built from: for each set of options, the cache class Caffeine
+ * creates and the class of the entries it holds.
+ */
+ private static final String[] CLASSES = {
+ // maximumSize
+ "SSMS", "PSMS",
+ // maximumWeight with a weigher
+ "SSMW", "PSMW",
+ // weakKeys
+ "WS", "FS",
+ // maximumSize with a removal listener
+ "SSLMS"
+ };
+
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ for (String name : CLASSES) {
+ hints.reflection().registerTypeIfPresent(classLoader, PACKAGE + name,
+ MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.ACCESS_DECLARED_FIELDS);
+ }
+ }
+
+}
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index 19b9c44e2cd..d4b931350b4 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -3,6 +3,7 @@ org.apache.grails.core.aot.AbstractBeanDefinitionExcludeFilter
org.springframework.aot.hint.RuntimeHintsRegistrar=\
org.apache.grails.core.aot.BeanRegistrarRuntimeHints,\
+org.apache.grails.core.aot.CaffeineRuntimeHints,\
org.apache.grails.core.aot.GrailsApiRuntimeHints,\
org.apache.grails.core.aot.GrailsBannerRuntimeHints,\
org.apache.grails.core.aot.GrailsClosureRuntimeHints,\
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/CaffeineRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/CaffeineRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..8ebd2ba7e73
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/CaffeineRuntimeHintsSpec.groovy
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import java.lang.reflect.Field
+
+import com.github.benmanes.caffeine.cache.Cache
+import com.github.benmanes.caffeine.cache.Caffeine
+import com.github.benmanes.caffeine.cache.RemovalListener
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import spock.lang.Shared
+import spock.lang.Specification
+
+/**
+ * Covers the classes the framework's caches are built from being creatable in an image.
+ *
+ * The names are Caffeine's, so each set of options the framework builds a cache with is built here and
+ * the classes Caffeine chose for it are read back: a Caffeine upgrade that renames them fails this rather
+ * than an image.
+ */
+class CaffeineRuntimeHintsSpec extends Specification {
+
+ @Shared
+ RuntimeHints hints = new RuntimeHints()
+
+ void setupSpec() {
+ new CaffeineRuntimeHints().registerHints(hints, getClass().classLoader)
+ }
+
+ void 'a cache built #options is built from classes that can be created'() {
+ when: 'a cache is built the way the framework builds one'
+ def classes = classesOf(cache)
+
+ then: 'both the cache class and the class of its entries are registered'
+ classes.every {
+ RuntimeHintsPredicates.reflection().onType(it)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.ACCESS_DECLARED_FIELDS)
+ .test(hints)
+ }
+
+ where:
+ options | cache
+ 'with a bound on the number of entries' | Caffeine.newBuilder().maximumSize(10).build()
+ 'with a bound on their weight' | Caffeine.newBuilder().maximumWeight(10).weigher { k, v -> 1 }.build()
+ 'with weak keys' | Caffeine.newBuilder().weakKeys().build()
+ 'with a bound and a removal listener' | Caffeine.newBuilder().removalListener({ k, v, cause -> } as RemovalListener)
+ .executor(Runnable::run).maximumSize(10).build()
+ }
+
+ /** The cache class Caffeine created for the cache, and the class of the entries it holds. */
+ private static List> classesOf(Cache cache) {
+ Object local = read(cache, 'cache')
+ [local.getClass(), read(local, 'nodeFactory').getClass()]
+ }
+
+ private static Object read(Object target, String name) {
+ Class> type = target.getClass()
+ while (type != null) {
+ Field field = type.declaredFields.find { it.name == name }
+ if (field != null) {
+ field.accessible = true
+ return field.get(target)
+ }
+ type = type.superclass
+ }
+ throw new IllegalStateException("No field '${name}' in ${target.getClass()}")
+ }
+}
From 3310a656609540cf23d66aaec6a3a60e3b49a109 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:28 -0700
Subject: [PATCH 16/39] Register the reflection compiled Groovy implies, read
from its bytecode
Some of what a Groovy class does is answered by reflection however it was
compiled: an enum chooses its constructor through Groovy, a closure passed for
an interface becomes a JDK proxy, a class implementing a trait initializes it
through a dynamic call to the trait's helpers, Spring injects annotated members
reflectively, and a Groovy object given a property is first asked whether it
overrides setProperty. A native image answers none of it unless asked, and
grails.util.Environment, the first thing an application touches, is a Groovy
enum.
The hints are read from the bytecode while they are written: the framework's
packages by a registrar, the application's packages -- the ones its
application class names -- by a bean factory processor.
---
...BeanFactoryInitializationAotProcessor.java | 112 ++++++
.../grails/core/aot/BytecodeRuntimeHints.java | 365 ++++++++++++++++++
.../resources/META-INF/spring/aot.factories | 2 +
.../NativeApplicationFixtures.groovy | 66 ++++
...ctoryInitializationAotProcessorSpec.groovy | 110 ++++++
.../grails/core/aot/BytecodeFixtures.groovy | 86 +++++
.../core/aot/BytecodeRuntimeHintsSpec.groovy | 124 ++++++
7 files changed, 865 insertions(+)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessor.java
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
create mode 100644 grails-core/src/test/groovy/com/example/nativeapp/NativeApplicationFixtures.groovy
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec.groovy
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessor.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessor.java
new file mode 100644
index 00000000000..45d354a5e8f
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessor.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.core.io.support.ResourcePatternResolver;
+import org.springframework.util.ClassUtils;
+
+import grails.boot.config.GrailsAutoConfiguration;
+
+/**
+ * Registers the reflection the application's own classes imply, read from their bytecode the way
+ * {@link BytecodeRuntimeHints} reads the framework's: creating a Groovy enum's constants, initializing a
+ * trait from the classes implementing it, turning a closure into the interface a method takes, asking a
+ * Groovy class about its methods, and the members Spring injects or calls through an annotation.
+ *
+ * {@link BytecodeRuntimeHints} covers the framework's packages. An application's classes are in
+ * its own, which are only known once the application is: they are the packages its application class
+ * names, the same ones the framework scans for its artefacts. Without this, an application declaring a
+ * Groovy enum -- a status on a domain class, say -- could not use it in an image, because the enum could not
+ * create its constants.
+ *
+ * @since 9.0
+ */
+public class ApplicationBytecodeBeanFactoryInitializationAotProcessor implements BeanFactoryInitializationAotProcessor {
+
+ private static final Log logger = LogFactory.getLog(ApplicationBytecodeBeanFactoryInitializationAotProcessor.class);
+
+ @Override
+ @Nullable
+ public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
+ Set packages = applicationPackages(beanFactory);
+ if (packages.isEmpty()) {
+ return null;
+ }
+ String[] patterns = packages.stream()
+ .map(name -> ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
+ ClassUtils.convertClassNameToResourcePath(name) + "/**/*.class")
+ .toArray(String[]::new);
+ ClassLoader classLoader = beanFactory.getBeanClassLoader();
+ return (generationContext, beanFactoryInitializationCode) ->
+ BytecodeRuntimeHints.registerFoundIn(generationContext.getRuntimeHints(), classLoader, patterns);
+ }
+
+ /**
+ * The packages the application's classes are in, as its application class names them, or none if this is
+ * not a Grails application context.
+ */
+ private Set applicationPackages(ConfigurableListableBeanFactory beanFactory) {
+ Set packages = new LinkedHashSet<>();
+ for (String name : beanFactory.getBeanDefinitionNames()) {
+ String className = beanFactory.getBeanDefinition(name).getBeanClassName();
+ if (className == null) {
+ continue;
+ }
+ Class> beanClass;
+ try {
+ beanClass = ClassUtils.forName(className, beanFactory.getBeanClassLoader());
+ }
+ catch (ClassNotFoundException | LinkageError ex) {
+ continue;
+ }
+ if (GrailsAutoConfiguration.class.isAssignableFrom(beanClass) && beanClass != GrailsAutoConfiguration.class) {
+ packages.addAll(packagesNamedBy(beanClass));
+ }
+ }
+ return packages;
+ }
+
+ /**
+ * The packages an application class names. An instance is created only to ask, as the framework does
+ * when it scans for the application's artefacts, because the list is a method the compiler writes into
+ * the class.
+ */
+ private Collection packagesNamedBy(Class> applicationClass) {
+ try {
+ return ((GrailsAutoConfiguration) applicationClass.getDeclaredConstructor().newInstance()).packageNames();
+ }
+ catch (ReflectiveOperationException | RuntimeException | LinkageError ex) {
+ logger.debug("Unable to ask " + applicationClass.getName() + " for its packages", ex);
+ String packageName = applicationClass.getPackageName();
+ return packageName.isEmpty() ? Set.of() : Set.of(packageName);
+ }
+ }
+
+}
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
new file mode 100644
index 00000000000..ff41e58d49a
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
@@ -0,0 +1,365 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import groovy.lang.GroovyObject;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.ExecutableMode;
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+import org.springframework.aot.hint.TypeReference;
+import org.springframework.asm.AnnotationVisitor;
+import org.springframework.asm.ClassReader;
+import org.springframework.asm.ClassVisitor;
+import org.springframework.asm.FieldVisitor;
+import org.springframework.asm.Handle;
+import org.springframework.asm.MethodVisitor;
+import org.springframework.asm.SpringAsmInfo;
+import org.springframework.asm.Type;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
+import org.springframework.core.io.support.ResourcePatternResolver;
+import org.springframework.util.ClassUtils;
+
+import org.apache.grails.common.aot.RegistrableTypes;
+
+/**
+ * Registers the reflection the framework's own compiled classes imply, read from their bytecode.
+ *
+ * Some of what a class does at run time is answered by reflection however it was compiled, and an image
+ * answers none of it unless it was asked to:
+ *
+ *
+ * - A Groovy enum creates its constants by choosing a constructor through Groovy rather than by calling
+ * one, so its constructors have to be visible. {@code grails.util.Environment} is one, and it is the first
+ * thing an application touches: without this an image fails before Spring has started, with "Could not
+ * find matching constructor".
+ * - A closure passed where a method takes an interface -- {@code removeIf}, {@code forEach},
+ * {@code computeIfAbsent}, a plugin's {@code BeanRegistrar} -- is turned into that interface by a JDK proxy
+ * created as the call is made. An image creates a proxy only for an interface it was told about, and
+ * refuses the rest with {@code MissingReflectionRegistrationError}.
+ * - A class implementing a trait initializes it from its constructor by calling the trait's helper class
+ * through {@code ScriptBytecodeAdapter.invokeMethodN}, a dynamic call. The framework's traits are on the
+ * application class, the controllers, the tag libraries and the domain classes, so without this none of
+ * them can be created: the first to fail is the application class itself, with "No signature of static
+ * method: $init$".
+ * - A member annotated for Spring to inject or call -- {@code @Autowired}, {@code @Value},
+ * {@code @Inject}, {@code @Resource}, {@code @PostConstruct}, {@code @PreDestroy} -- is set or called
+ * reflectively by the post-processor that handles the annotation. Many of the framework's beans are
+ * created by a supplier and declared as an interface, so their classes are known only once they exist,
+ * and the members are found here instead: the link generator's collaborators were left unset without
+ * this.
+ * - A Groovy object given a property dynamically is first asked, through {@code Class.getMethod}, whether
+ * it overrides {@code setProperty}. An image answers that only for a class registered as a type, so every
+ * Groovy class is registered as one: without it the bean DSL could not set the first bean's options, with
+ * {@code NoSuchMethodException} for a method the class plainly has. Only the type is registered -- calls
+ * are made through the interfaces the class implements, which are registered for what they declare.
+ *
+ *
+ * All of it is found by reading the bytecode while the hints are written, which happens during the build
+ * on an ordinary JVM with the full classpath: an enum is a class extending {@code Enum} that implements
+ * {@code GroovyObject}, a coercion is an invokedynamic {@code cast} from {@code Closure} to an interface, a
+ * trait's helpers are the classes Groovy names {@code $Trait$Helper}, {@code $Trait$FieldHelper} and
+ * {@code $Trait$StaticFieldHelper}, an injected member carries its annotation, and a Groovy class is one
+ * that implements {@code GroovyObject}, directly or through a superclass. The framework compiles
+ * against optional integrations, so a class that cannot be loaded here is skipped rather than registered,
+ * as {@link GrailsClosureRuntimeHints} does for closures.
+ *
+ * @since 9.0
+ */
+public class BytecodeRuntimeHints implements RuntimeHintsRegistrar {
+
+ private static final Log logger = LogFactory.getLog(BytecodeRuntimeHints.class);
+
+ /** Where the framework's classes are found: its own packages, old and new. */
+ private static final String[] PATTERNS = {
+ ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "grails/**/*.class",
+ ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "org/grails/**/*.class",
+ ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "org/apache/grails/**/*.class"
+ };
+
+ private static final String ENUM = "java/lang/Enum";
+
+ private static final String GROOVY_OBJECT = "groovy/lang/GroovyObject";
+
+ private static final String INDY_INTERFACE = "org/codehaus/groovy/vmplugin/v8/IndyInterface";
+
+ private static final String CAST = "cast";
+
+ private static final String CLOSURE = "Lgroovy/lang/Closure;";
+
+ /** How Groovy names the classes that carry a trait's methods and fields. */
+ private static final String[] TRAIT_HELPER_SUFFIXES = {
+ "$Trait$Helper", "$Trait$FieldHelper", "$Trait$StaticFieldHelper"
+ };
+
+ /** The annotations a member is injected or called through, as they appear in bytecode. */
+ private static final Set SPRING_ANNOTATIONS = Set.of(
+ "Lorg/springframework/beans/factory/annotation/Autowired;",
+ "Lorg/springframework/beans/factory/annotation/Value;",
+ "Ljakarta/inject/Inject;",
+ "Ljakarta/annotation/Resource;",
+ "Ljakarta/annotation/PostConstruct;",
+ "Ljakarta/annotation/PreDestroy;");
+
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ registerFoundIn(hints, classLoader, PATTERNS);
+ }
+
+ /**
+ * Registers the reflection the classes the given patterns match imply. Also used for the application's
+ * own packages, which an application's classes are in and the framework's patterns do not cover.
+ *
+ * @param hints where the hints are registered
+ * @param classLoader the loader the classes are read and loaded from
+ * @param patterns resource patterns matching class files
+ */
+ static void registerFoundIn(RuntimeHints hints, @Nullable ClassLoader classLoader, String... patterns) {
+ ClassLoader loader = (classLoader != null) ? classLoader : ClassUtils.getDefaultClassLoader();
+ ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(loader);
+ Findings findings = new Findings();
+ for (String pattern : patterns) {
+ Resource[] resources;
+ try {
+ resources = resolver.getResources(pattern);
+ }
+ catch (IOException ex) {
+ logger.warn("Unable to scan for classes matching " + pattern, ex);
+ continue;
+ }
+ for (Resource resource : resources) {
+ read(resource, findings);
+ }
+ }
+ findings.register(hints, loader);
+ }
+
+ private static void read(Resource resource, Findings findings) {
+ try (InputStream input = resource.getInputStream()) {
+ new ClassReader(input).accept(new FindingClassVisitor(findings, resource),
+ ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
+ }
+ catch (IOException | RuntimeException ex) {
+ logger.debug("Unable to read " + resource, ex);
+ }
+ }
+
+ /**
+ * The type, or none if it cannot be loaded here: registering a type that does not load fails the image
+ * build, and a closure cast to an abstract class is not proxied by the JDK, so only an interface is.
+ */
+ @Nullable
+ private static Class> load(String type, ClassLoader loader) {
+ if (!RegistrableTypes.loads(type, loader)) {
+ return null;
+ }
+ try {
+ return ClassUtils.forName(type, loader);
+ }
+ catch (ClassNotFoundException | LinkageError ex) {
+ return null;
+ }
+ }
+
+ /**
+ * Whether the class is a Groovy class that can be registered: one implementing {@code GroovyObject}, that
+ * loads here and whose bytecode names nothing absent here. A closure is left to
+ * {@link GrailsClosureRuntimeHints}, which registers more of it.
+ */
+ private static boolean isGroovyClass(String className, Resource resource, ClassLoader loader) {
+ if (className.contains("$_")) {
+ return false;
+ }
+ Class> type = load(className, loader);
+ if (type == null || type.isInterface() || !GroovyObject.class.isAssignableFrom(type)) {
+ return false;
+ }
+ try {
+ return RegistrableTypes.referencesLoad(resource.getInputStream(), loader);
+ }
+ catch (IOException ex) {
+ return false;
+ }
+ }
+
+ /** A method by its name and the names of its parameter types. */
+ private record MethodSignature(String name, List parameterTypes) {
+ }
+
+ /**
+ * What the bytecode was found to need, by the names it gives the types. Registered by name rather than
+ * by class: a trait's helper is declared nested in the trait under a name containing a {@code $}, so a
+ * name rebuilt from the class -- the trait's, a {@code $}, the helper's simple name -- drops the
+ * {@code Trait} in the middle and names a class that does not exist.
+ */
+ private static final class Findings {
+
+ private final Set enums = new LinkedHashSet<>();
+
+ private final Set coercedTo = new LinkedHashSet<>();
+
+ private final Set traitHelpers = new LinkedHashSet<>();
+
+ private final Map> injectedFields = new LinkedHashMap<>();
+
+ private final Map> invokedMethods = new LinkedHashMap<>();
+
+ /** Every class read, with where it was read from, to be asked whether it is a Groovy class. */
+ private final Map classes = new LinkedHashMap<>();
+
+ private void register(RuntimeHints hints, ClassLoader loader) {
+ for (String type : enums) {
+ if (load(type, loader) != null) {
+ hints.reflection().registerType(TypeReference.of(type), MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
+ }
+ }
+ for (String type : coercedTo) {
+ Class> coerced = load(type, loader);
+ if (coerced != null && coerced.isInterface()) {
+ hints.proxies().registerJdkProxy(TypeReference.of(type));
+ }
+ }
+ for (String type : traitHelpers) {
+ if (load(type, loader) != null) {
+ hints.reflection().registerType(TypeReference.of(type), MemberCategory.INVOKE_DECLARED_METHODS);
+ }
+ }
+ injectedFields.forEach((type, fields) -> {
+ if (load(type, loader) != null) {
+ hints.reflection().registerType(TypeReference.of(type), builder -> fields.forEach(builder::withField));
+ }
+ });
+ invokedMethods.forEach((type, methods) -> {
+ if (load(type, loader) != null) {
+ hints.reflection().registerType(TypeReference.of(type), builder -> methods.forEach(method ->
+ builder.withMethod(method.name(), method.parameterTypes(), ExecutableMode.INVOKE)));
+ }
+ });
+ int groovyClasses = 0;
+ for (Map.Entry found : classes.entrySet()) {
+ if (isGroovyClass(found.getKey(), found.getValue(), loader)) {
+ hints.reflection().registerType(TypeReference.of(found.getKey()));
+ groovyClasses++;
+ }
+ }
+ logger.debug("Registered " + groovyClasses + " Groovy classes, " + enums.size() + " Groovy enums, " +
+ traitHelpers.size() + " trait helpers, " +
+ "proxies for " + coercedTo.size() + " interfaces closures are coerced to, and the injected " +
+ "members of " + (injectedFields.size() + invokedMethods.size()) + " classes");
+ }
+ }
+
+ /**
+ * Collects whether a class is a Groovy enum or a trait's helper, the interfaces its closures are cast to,
+ * and the members it has annotated for Spring.
+ */
+ private static final class FindingClassVisitor extends ClassVisitor {
+
+ private final Findings findings;
+
+ private final Resource resource;
+
+ private String className = "";
+
+ private FindingClassVisitor(Findings findings, Resource resource) {
+ super(SpringAsmInfo.ASM_VERSION);
+ this.findings = findings;
+ this.resource = resource;
+ }
+
+ @Override
+ public void visit(int version, int access, String name, String signature, String superName,
+ String[] interfaces) {
+ className = ClassUtils.convertResourcePathToClassName(name);
+ findings.classes.put(className, resource);
+ if (ENUM.equals(superName) && interfaces != null && Arrays.asList(interfaces).contains(GROOVY_OBJECT)) {
+ findings.enums.add(className);
+ }
+ for (String suffix : TRAIT_HELPER_SUFFIXES) {
+ if (className.endsWith(suffix)) {
+ findings.traitHelpers.add(className);
+ }
+ }
+ }
+
+ @Override
+ public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
+ return new FieldVisitor(SpringAsmInfo.ASM_VERSION) {
+ @Override
+ public AnnotationVisitor visitAnnotation(String annotation, boolean visible) {
+ if (SPRING_ANNOTATIONS.contains(annotation)) {
+ findings.injectedFields.computeIfAbsent(className, type -> new LinkedHashSet<>()).add(name);
+ }
+ return null;
+ }
+ };
+ }
+
+ @Override
+ public MethodVisitor visitMethod(int access, String name, String descriptor, String signature,
+ String[] exceptions) {
+ return new MethodVisitor(SpringAsmInfo.ASM_VERSION) {
+ @Override
+ public AnnotationVisitor visitAnnotation(String annotation, boolean visible) {
+ if (SPRING_ANNOTATIONS.contains(annotation)) {
+ List parameterTypes = new ArrayList<>();
+ for (Type parameter : Type.getArgumentTypes(descriptor)) {
+ parameterTypes.add(TypeReference.of(parameter.getClassName()));
+ }
+ findings.invokedMethods.computeIfAbsent(className, type -> new LinkedHashSet<>())
+ .add(new MethodSignature(name, parameterTypes));
+ }
+ return null;
+ }
+
+ @Override
+ public void visitInvokeDynamicInsn(String methodName, String methodDescriptor, Handle bootstrap,
+ Object... bootstrapArguments) {
+ if (!CAST.equals(methodName) || !INDY_INTERFACE.equals(bootstrap.getOwner())) {
+ return;
+ }
+ Type[] arguments = Type.getArgumentTypes(methodDescriptor);
+ Type target = Type.getReturnType(methodDescriptor);
+ if (arguments.length == 1 && CLOSURE.equals(arguments[0].getDescriptor()) &&
+ target.getSort() == Type.OBJECT) {
+ findings.coercedTo.add(target.getClassName());
+ }
+ }
+ };
+ }
+
+ }
+
+}
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index d4b931350b4..30295a03baa 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -3,6 +3,7 @@ org.apache.grails.core.aot.AbstractBeanDefinitionExcludeFilter
org.springframework.aot.hint.RuntimeHintsRegistrar=\
org.apache.grails.core.aot.BeanRegistrarRuntimeHints,\
+org.apache.grails.core.aot.BytecodeRuntimeHints,\
org.apache.grails.core.aot.CaffeineRuntimeHints,\
org.apache.grails.core.aot.GrailsApiRuntimeHints,\
org.apache.grails.core.aot.GrailsBannerRuntimeHints,\
@@ -17,4 +18,5 @@ org.apache.grails.core.aot.AutowireModeBeanRegistrationAotProcessor,\
org.apache.grails.core.aot.VarargsBeanRegistrationAotProcessor
org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor=\
+org.apache.grails.core.aot.ApplicationBytecodeBeanFactoryInitializationAotProcessor,\
org.apache.grails.core.aot.ArtefactClassesBeanFactoryInitializationAotProcessor
diff --git a/grails-core/src/test/groovy/com/example/nativeapp/NativeApplicationFixtures.groovy b/grails-core/src/test/groovy/com/example/nativeapp/NativeApplicationFixtures.groovy
new file mode 100644
index 00000000000..35129c140da
--- /dev/null
+++ b/grails-core/src/test/groovy/com/example/nativeapp/NativeApplicationFixtures.groovy
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.example.nativeapp
+
+import java.util.stream.LongStream
+
+import groovy.transform.CompileStatic
+
+import grails.boot.config.GrailsAutoConfiguration
+
+/**
+ * An application in a package of its own, outside the framework's, naming that package as the one its
+ * classes are in.
+ */
+class NativeApplicationFixture extends GrailsAutoConfiguration {
+
+ @Override
+ Collection packageNames() {
+ ['com.example.nativeapp']
+ }
+}
+
+/** A status an application declares, as a domain class would. */
+enum OrderStatusFixture {
+ OPEN,
+ CLOSED
+}
+
+/** A trait an application declares. */
+trait AuditedFixture {
+
+ String auditedBy = 'system'
+}
+
+/** A class implementing it. */
+@CompileStatic
+class AuditedOrderFixture implements AuditedFixture {
+}
+
+/**
+ * A closure an application passes where a method takes an interface. {@code LongBinaryOperator} because the
+ * framework coerces no closure to it.
+ */
+@CompileStatic
+class TotalsFixture {
+
+ static long total(long upTo) {
+ LongStream.range(0, upTo).reduce(0L) { long left, long right -> left + right }
+ }
+}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec.groovy
new file mode 100644
index 00000000000..22b343029f4
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec.groovy
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import java.util.function.LongBinaryOperator
+
+import org.springframework.aot.generate.ClassNameGenerator
+import org.springframework.aot.generate.DefaultGenerationContext
+import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.TypeReference
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import org.springframework.beans.factory.aot.BeanFactoryInitializationCode
+import org.springframework.context.support.GenericApplicationContext
+import org.springframework.javapoet.ClassName
+import spock.lang.Specification
+
+import com.example.nativeapp.AuditedFixture
+import com.example.nativeapp.AuditedOrderFixture
+import com.example.nativeapp.NativeApplicationFixture
+import com.example.nativeapp.OrderStatusFixture
+import com.example.nativeapp.TotalsFixture
+
+/**
+ * Covers what Groovy does reflectively on behalf of an application's own classes being possible in an image.
+ *
+ * The framework's packages are covered by {@link BytecodeRuntimeHints}; an application's are the
+ * ones its application class names. Without this an application could not use a Groovy enum it declared.
+ */
+class ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec extends Specification {
+
+ GenericApplicationContext context = new GenericApplicationContext()
+
+ void cleanup() {
+ context.close()
+ }
+
+ private RuntimeHints hints() {
+ def contribution = new ApplicationBytecodeBeanFactoryInitializationAotProcessor()
+ .processAheadOfTime(context.beanFactory)
+ def generation = new DefaultGenerationContext(
+ new ClassNameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
+ contribution.applyTo(generation, Mock(BeanFactoryInitializationCode))
+ generation.runtimeHints
+ }
+
+ void 'a Groovy enum the application declares can have its constants created'() {
+ given: 'an application whose classes are in a package of its own'
+ context.registerBean('application', NativeApplicationFixture)
+
+ when:
+ def hints = hints()
+
+ then:
+ RuntimeHintsPredicates.reflection().onType(OrderStatusFixture)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+
+ void 'a trait the application declares can be initialized'() {
+ given:
+ context.registerBean('application', NativeApplicationFixture)
+
+ when:
+ def hints = hints()
+
+ then:
+ RuntimeHintsPredicates.reflection().onType(TypeReference.of(AuditedFixture.name + '$Trait$Helper'))
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS).test(hints)
+ }
+
+ void 'an interface the application coerces a closure to can be proxied'() {
+ given:
+ context.registerBean('application', NativeApplicationFixture)
+
+ when:
+ def hints = hints()
+
+ then:
+ RuntimeHintsPredicates.proxies().forInterfaces(LongBinaryOperator).test(hints)
+ }
+
+ void 'a context with no application class contributes nothing'() {
+ expect: 'a plain Spring application being generated names no packages'
+ new ApplicationBytecodeBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory) == null
+ }
+
+ void 'the fixtures do what the hints are for'() {
+ expect:
+ OrderStatusFixture.values()*.name() == ['OPEN', 'CLOSED']
+ new AuditedOrderFixture().auditedBy == 'system'
+ TotalsFixture.total(4) == 6
+ }
+}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
new file mode 100644
index 00000000000..2df7d989e64
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import java.util.stream.IntStream
+
+import groovy.transform.CompileStatic
+
+import jakarta.annotation.PostConstruct
+import jakarta.annotation.PreDestroy
+
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.beans.factory.annotation.Value
+
+/**
+ * A Groovy enum, which creates its constants by choosing a constructor through Groovy. In a package
+ * {@link BytecodeRuntimeHints} scans, as the framework's own are.
+ */
+enum GroovyEnumFixture {
+ FIRST,
+ SECOND
+}
+
+/**
+ * A closure passed where a method takes an interface, which Groovy turns into that interface with a
+ * JDK proxy even under static compilation. {@code IntBinaryOperator} because nothing in the framework
+ * coerces a closure to it, so finding it proves this class was read.
+ */
+@CompileStatic
+class ClosureCoercionFixture {
+
+ static int sum(int upTo) {
+ IntStream.range(0, upTo).reduce(0) { int left, int right -> left + right }
+ }
+}
+
+/**
+ * A trait with a field, so Groovy writes both a helper and a field helper for it, and a class implementing
+ * it initializes it from its constructor through the helper.
+ */
+trait GreetingTraitFixture {
+
+ String greeting = 'hello'
+}
+
+/** A class implementing the trait, which is what calls the helper. */
+@CompileStatic
+class GreeterFixture implements GreetingTraitFixture {
+}
+
+/**
+ * A bean whose members Spring injects and calls through annotations, as the link generator's are, which a
+ * scan finds whatever the bean was declared as.
+ */
+class AnnotatedMembersFixture {
+
+ @Autowired
+ private Object collaborator
+
+ @Value('${fixture.setting:default}')
+ String setting
+
+ @PostConstruct
+ void initialize() {
+ }
+
+ @PreDestroy
+ void close() {
+ }
+}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..5943624b271
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import java.util.function.IntBinaryOperator
+
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.TypeReference
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import spock.lang.Shared
+import spock.lang.Specification
+
+import grails.util.Environment
+
+/**
+ * Covers what Groovy does reflectively on behalf of the framework's classes being possible in an
+ * image: creating a Groovy enum's constants, and turning a closure into the interface a method takes.
+ * Both happen even under static compilation, and an image does neither unless it was asked to.
+ */
+class BytecodeRuntimeHintsSpec extends Specification {
+
+ @Shared
+ RuntimeHints hints = new RuntimeHints()
+
+ void setupSpec() {
+ new BytecodeRuntimeHints().registerHints(hints, getClass().classLoader)
+ }
+
+ void 'a Groovy enum can have its constants created'() {
+ expect: 'each constant is created by choosing a constructor through Groovy'
+ RuntimeHintsPredicates.reflection().onType(GroovyEnumFixture)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+
+ void 'the environment can be initialized'() {
+ expect: 'it is the first thing an application touches, so an image without it stops before Spring starts'
+ RuntimeHintsPredicates.reflection().onType(Environment)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+
+ void 'a class that is not an enum is not registered for its constructors'() {
+ expect: 'what a scan of every class registers has to stay bounded to what needs it'
+ !RuntimeHintsPredicates.reflection().onType(ClosureCoercionFixture)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+
+ void 'an interface a closure is coerced to can be proxied'() {
+ expect: 'the closure becomes the interface through a JDK proxy created as the call is made'
+ RuntimeHintsPredicates.proxies().forInterfaces(IntBinaryOperator).test(hints)
+ }
+
+ void 'a trait can be initialized by the classes implementing it'() {
+ given: 'the helpers Groovy writes for a trait with a field, by the names an image is told'
+ def helper = TypeReference.of(GreetingTraitFixture.name + '$Trait$Helper')
+ def fieldHelper = TypeReference.of(GreetingTraitFixture.name + '$Trait$FieldHelper')
+
+ expect: 'an implementing class calls the helper from its constructor through a dynamic call'
+ RuntimeHintsPredicates.reflection().onType(helper)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS).test(hints)
+ RuntimeHintsPredicates.reflection().onType(fieldHelper)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS).test(hints)
+ }
+
+ void 'a trait helper is registered under the name its class has'() {
+ when: 'the names an image is told are read back'
+ def names = hints.reflection().typeHints().map { it.type.name }.toList()
+
+ then: 'a name rebuilt from the helper class drops the Trait in the middle and names nothing'
+ names.contains(GreetingTraitFixture.name + '$Trait$Helper')
+ !names.contains(GreetingTraitFixture.name + '$Helper')
+ }
+
+ void 'the application class can be created'() {
+ expect: 'it implements GrailsApplicationClass, and was the first class an image could not create'
+ RuntimeHintsPredicates.reflection().onType(TypeReference.of('grails.core.GrailsApplicationClass$Trait$Helper'))
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS).test(hints)
+ }
+
+ void 'the members Spring injects or calls through an annotation can be reached'() {
+ expect: 'a bean created by a supplier and declared as an interface is known only once it exists, so ' +
+ 'its members are found in its bytecode instead'
+ RuntimeHintsPredicates.reflection().onFieldAccess(AnnotatedMembersFixture, 'collaborator').test(hints)
+ RuntimeHintsPredicates.reflection().onFieldAccess(AnnotatedMembersFixture, 'setting').test(hints)
+ RuntimeHintsPredicates.reflection().onMethodInvocation(AnnotatedMembersFixture, 'initialize').test(hints)
+ RuntimeHintsPredicates.reflection().onMethodInvocation(AnnotatedMembersFixture, 'close').test(hints)
+ }
+
+ void 'a Groovy class can be asked about its methods'() {
+ expect: 'a Groovy object given a property dynamically is first asked whether it overrides setProperty'
+ RuntimeHintsPredicates.reflection().onType(ClosureCoercionFixture).test(hints)
+ }
+
+ void 'a class that is not a Groovy class is not registered for that'() {
+ expect: 'a Java class in a scanned package, which no Groovy dispatch asks about'
+ !RuntimeHintsPredicates.reflection().onType(CaffeineRuntimeHints).test(hints)
+ }
+
+ void 'the coercion still works'() {
+ expect: 'the fixture is the code the hint is for, so it has to do what it says'
+ ClosureCoercionFixture.sum(4) == 6
+ }
+
+ void 'the trait still initializes'() {
+ expect: 'the fixture is the code the hint is for, so it has to do what it says'
+ new GreeterFixture().greeting == 'hello'
+ }
+}
From 9e449d0a2b303b04d36b11f67943845104886704 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:28 -0700
Subject: [PATCH 17/39] Register the artefacts and the classes that represent
them
Every artefact is represented by a GrailsClass its handler creates through a
constructor taking the artefact's class, and each kind of artefact is read
reflectively. The build registers the application's own classes, but not the
artefacts that come from the framework, like the default URL mappings, nor the
ones plugins provide. They are registered from the assembled application,
using the new ArtefactHandlerAdapter.getGrailsClassImpl().
---
.../grails/core/ArtefactHandlerAdapter.java | 11 ++
...BeanFactoryInitializationAotProcessor.java | 142 ++++++++++++++++
.../resources/META-INF/spring/aot.factories | 3 +-
...ctoryInitializationAotProcessorSpec.groovy | 152 ++++++++++++++++++
4 files changed, 307 insertions(+), 1 deletion(-)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessor.java
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessorSpec.groovy
diff --git a/grails-core/src/main/groovy/grails/core/ArtefactHandlerAdapter.java b/grails-core/src/main/groovy/grails/core/ArtefactHandlerAdapter.java
index 64d60362665..909ac653ae2 100644
--- a/grails-core/src/main/groovy/grails/core/ArtefactHandlerAdapter.java
+++ b/grails-core/src/main/groovy/grails/core/ArtefactHandlerAdapter.java
@@ -78,6 +78,17 @@ public String getType() {
return type;
}
+ /**
+ * The class {@link #newArtefactClass(Class)} creates to represent an artefact of this type, through its
+ * constructor taking the artefact class.
+ *
+ * @return the {@link GrailsClass} implementation this handler creates
+ * @since 9.0
+ */
+ public Class> getGrailsClassImpl() {
+ return grailsClassImpl;
+ }
+
/**
* Default implementation of {@link grails.core.ArtefactHandler#isArtefact(org.codehaus.groovy.ast.ClassNode)} which returns true if the ClassNode passes the
* {@link #isArtefactResource(org.grails.io.support.Resource)} method and the name of the ClassNode ends with the {@link #artefactSuffix}
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessor.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessor.java
new file mode 100644
index 00000000000..c93d526da4e
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessor.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.ReflectionHints;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+
+import grails.core.ArtefactHandler;
+import grails.core.ArtefactHandlerAdapter;
+import grails.core.GrailsApplication;
+import grails.plugins.GrailsPlugin;
+import grails.plugins.GrailsPluginManager;
+
+/**
+ * Registers what the framework reaches reflectively as it registers artefacts: the class that represents
+ * each kind of artefact, and the artefacts themselves -- the application's and the ones the plugins provide.
+ *
+ * Every artefact is represented by a {@code GrailsClass} its handler creates through a constructor
+ * taking the artefact's class -- a codec by {@code DefaultGrailsCodecClass}, a tag library by
+ * {@code DefaultGrailsTagLibClass}. And an artefact is read the way its kind needs: a codec created and
+ * given its collaborators through its setters, a URL mappings class asked for the {@code mappings} closure
+ * it declares, a controller for its actions. An image keeps none of those members unless asked, so an image
+ * built without these stopped while the plugins registered their artefacts, unable to find the constructor
+ * of the first codec's {@code GrailsClass}, and then while the URL mappings were evaluated, unable to find
+ * the closure the default mappings declare.
+ *
+ * The build registers the application's own classes from its output, but not the artefacts that come
+ * from the framework -- the default URL mappings are one the application holds without having written
+ * it -- nor what the plugins provide.
+ *
+ * Both are read from the application as it was assembled while the hints are written, which is the only
+ * place they are all known: a handler names its {@code GrailsClass} in code, and a plugin lists what it
+ * provides in a property rather than in its descriptor.
+ *
+ * @since 9.0
+ */
+public class ArtefactReflectionBeanFactoryInitializationAotProcessor implements BeanFactoryInitializationAotProcessor {
+
+ @Override
+ @Nullable
+ public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
+ Set> representations = representationsOf(beanFactory);
+ Set> artefacts = artefactsOf(beanFactory);
+ artefacts.addAll(providedByPlugins(beanFactory));
+ if (representations.isEmpty() && artefacts.isEmpty()) {
+ return null;
+ }
+ return (generationContext, beanFactoryInitializationCode) -> {
+ ReflectionHints reflection = generationContext.getRuntimeHints().reflection();
+ for (Class> representation : representations) {
+ reflection.registerType(representation, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
+ }
+ for (Class> artefact : artefacts) {
+ reflection.registerType(artefact, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
+ MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.INVOKE_PUBLIC_METHODS,
+ MemberCategory.ACCESS_DECLARED_FIELDS);
+ }
+ };
+ }
+
+ /**
+ * The {@code GrailsClass} each handler creates, or none if this is not a Grails application context -- a
+ * plain Spring one being generated has no {@code grailsApplication}.
+ */
+ private Set> representationsOf(ConfigurableListableBeanFactory beanFactory) {
+ Set> representations = new LinkedHashSet<>();
+ Object application = beanFactory.getSingleton(GrailsApplication.APPLICATION_ID);
+ if (!(application instanceof GrailsApplication grailsApplication)) {
+ return representations;
+ }
+ ArtefactHandler[] handlers = grailsApplication.getArtefactHandlers();
+ if (handlers == null) {
+ return representations;
+ }
+ for (ArtefactHandler handler : handlers) {
+ if (handler instanceof ArtefactHandlerAdapter adapter && adapter.getGrailsClassImpl() != null) {
+ representations.add(adapter.getGrailsClassImpl());
+ }
+ }
+ return representations;
+ }
+
+ /** The artefacts the application holds, whichever module they came from. */
+ private Set> artefactsOf(ConfigurableListableBeanFactory beanFactory) {
+ Set> artefacts = new LinkedHashSet<>();
+ Object application = beanFactory.getSingleton(GrailsApplication.APPLICATION_ID);
+ if (!(application instanceof GrailsApplication grailsApplication) || grailsApplication.getAllClasses() == null) {
+ return artefacts;
+ }
+ for (Class> artefact : grailsApplication.getAllClasses()) {
+ if (artefact != null) {
+ artefacts.add(artefact);
+ }
+ }
+ return artefacts;
+ }
+
+ /** The artefacts the plugins provide, which the application declares nowhere. */
+ private Set> providedByPlugins(ConfigurableListableBeanFactory beanFactory) {
+ Set> provided = new LinkedHashSet<>();
+ Object manager = beanFactory.getSingleton(GrailsPluginManager.BEAN_NAME);
+ if (!(manager instanceof GrailsPluginManager pluginManager)) {
+ return provided;
+ }
+ for (GrailsPlugin plugin : pluginManager.getAllPlugins()) {
+ Class>[] artefacts = plugin.getProvidedArtefacts();
+ if (artefacts != null) {
+ for (Class> artefact : artefacts) {
+ if (artefact != null) {
+ provided.add(artefact);
+ }
+ }
+ }
+ }
+ return provided;
+ }
+
+}
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index 30295a03baa..26b1f6d6e64 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -19,4 +19,5 @@ org.apache.grails.core.aot.VarargsBeanRegistrationAotProcessor
org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor=\
org.apache.grails.core.aot.ApplicationBytecodeBeanFactoryInitializationAotProcessor,\
-org.apache.grails.core.aot.ArtefactClassesBeanFactoryInitializationAotProcessor
+org.apache.grails.core.aot.ArtefactClassesBeanFactoryInitializationAotProcessor,\
+org.apache.grails.core.aot.ArtefactReflectionBeanFactoryInitializationAotProcessor
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessorSpec.groovy
new file mode 100644
index 00000000000..494abbd6e72
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessorSpec.groovy
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import org.springframework.aot.generate.ClassNameGenerator
+import org.springframework.aot.generate.DefaultGenerationContext
+import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import org.springframework.beans.factory.aot.BeanFactoryInitializationCode
+import org.springframework.context.support.GenericApplicationContext
+import org.springframework.javapoet.ClassName
+import spock.lang.Specification
+
+import grails.core.ArtefactHandlerAdapter
+import grails.core.DefaultGrailsApplication
+import grails.core.GrailsApplication
+import grails.plugins.GrailsPlugin
+import grails.plugins.GrailsPluginManager
+import org.grails.core.DefaultGrailsServiceClass
+import org.grails.core.DefaultGrailsUrlMappingsClass
+
+/**
+ * Covers what the framework creates reflectively as it registers artefacts being creatable in an image:
+ * the class each kind of artefact is represented by, and what the plugins provide.
+ *
+ * An image built without these stopped while the plugins registered their artefacts, unable to find
+ * the constructor of the first codec's {@code GrailsClass}.
+ */
+class ArtefactReflectionBeanFactoryInitializationAotProcessorSpec extends Specification {
+
+ GenericApplicationContext context = new GenericApplicationContext()
+
+ void cleanup() {
+ context.close()
+ }
+
+ private GrailsApplication application(Class>... classes) {
+ GrailsApplication application = new DefaultGrailsApplication(classes)
+ application.applicationContext = context
+ application.initialise()
+ context.beanFactory.registerSingleton(GrailsApplication.APPLICATION_ID, application)
+ application
+ }
+
+ private RuntimeHints hints() {
+ def contribution = new ArtefactReflectionBeanFactoryInitializationAotProcessor()
+ .processAheadOfTime(context.beanFactory)
+ def generation = new DefaultGenerationContext(
+ new ClassNameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
+ contribution.applyTo(generation, Mock(BeanFactoryInitializationCode))
+ generation.runtimeHints
+ }
+
+ private static boolean constructible(RuntimeHints hints, Class> type) {
+ RuntimeHintsPredicates.reflection().onType(type)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+
+ void 'the class a kind of artefact is represented by can be created'() {
+ given: 'an application with the artefact handlers the framework declares'
+ application()
+
+ when:
+ def hints = hints()
+
+ then: 'a handler creates it through a constructor taking the artefact class'
+ constructible(hints, DefaultGrailsServiceClass)
+ constructible(hints, DefaultGrailsUrlMappingsClass)
+ }
+
+ void 'every handler the application has is covered'() {
+ given:
+ def application = application()
+ def representations = application.artefactHandlers
+ .findAll { it instanceof ArtefactHandlerAdapter }
+ .collect { ((ArtefactHandlerAdapter) it).grailsClassImpl }
+
+ when:
+ def hints = hints()
+
+ then: 'whichever module declared it'
+ !representations.isEmpty()
+ representations.every { constructible(hints, it) }
+ }
+
+ void 'what a plugin provides can be created and given its collaborators'() {
+ given: 'a plugin providing an artefact, as the codecs plugin provides its codecs'
+ application()
+ context.beanFactory.registerSingleton(GrailsPluginManager.BEAN_NAME,
+ Stub(GrailsPluginManager) {
+ getAllPlugins() >> ([Stub(GrailsPlugin) {
+ getProvidedArtefacts() >> ([ProvidedCodecFixture] as Class[])
+ }] as GrailsPlugin[])
+ })
+
+ when:
+ def hints = hints()
+
+ then: 'it is created through its constructor, and its collaborators are set through its setters'
+ RuntimeHintsPredicates.reflection().onType(ProvidedCodecFixture)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS)
+ .test(hints)
+ }
+
+ void 'an artefact the application holds can be read the way its kind needs'() {
+ given: 'an application holding a URL mappings class it did not write, as it holds the default mappings'
+ application(DefaultUrlMappingsFixture)
+
+ when:
+ def hints = hints()
+
+ then: 'its mappings closure is read from the field it declares'
+ RuntimeHintsPredicates.reflection().onType(DefaultUrlMappingsFixture)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS,
+ MemberCategory.ACCESS_DECLARED_FIELDS)
+ .test(hints)
+ }
+
+ void 'a context that is not a Grails application contributes nothing'() {
+ expect: 'a plain Spring application being generated has no grailsApplication and no plugins to ask'
+ new ArtefactReflectionBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory) == null
+ }
+
+ static class ProvidedCodecFixture {
+
+ GrailsApplication grailsApplication
+ }
+
+ static class DefaultUrlMappingsFixture {
+
+ static mappings = {
+ }
+ }
+}
From 7bee820c1fd147042deca1e3abddf7a82189e290 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:28 -0700
Subject: [PATCH 18/39] Register the beans the plugins declare as the
application starts
Spring generates code only for the definitions it is shown. A BeanRegistrar's
beans are left out of generation, and the bean DSL's are declared again at run
time, so both are created the ordinary, reflective way: through a constructor,
their setters, and their annotated members. Every bean definition with a class
is covered, however a plugin declared it.
---
...BeanFactoryInitializationAotProcessor.java | 201 +++++++++++++++++
.../resources/META-INF/spring/aot.factories | 3 +-
...ctoryInitializationAotProcessorSpec.groovy | 206 ++++++++++++++++++
3 files changed, 409 insertions(+), 1 deletion(-)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessor.java
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessor.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessor.java
new file mode 100644
index 00000000000..bf6328eb953
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessor.java
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AnnotatedElement;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import jakarta.annotation.PostConstruct;
+import jakarta.annotation.PreDestroy;
+import jakarta.annotation.Resource;
+import jakarta.inject.Inject;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.ExecutableMode;
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.ReflectionHints;
+import org.springframework.beans.factory.NoSuchBeanDefinitionException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.beans.factory.support.AbstractBeanDefinition;
+import org.springframework.core.annotation.AnnotatedElementUtils;
+import org.springframework.util.ClassUtils;
+import org.springframework.util.ReflectionUtils;
+
+/**
+ * Registers what Spring reaches reflectively when it creates and wires the beans the framework declares.
+ *
+ * Spring generates the code that creates a bean only for the definitions it is shown, and the plugins
+ * declare theirs as the application starts: a {@code BeanRegistrar}'s beans are left out of generation and
+ * declared again, and the bean DSL's are declared again by the plugins at run time. Those are created the
+ * ordinary way -- through a constructor, given their properties through their setters, and given their
+ * {@code @Autowired}, {@code @Value} and {@code @Inject} members by the post-processor that handles them --
+ * and all of it is reflective. An image keeps none of it unless asked, so an image built without these
+ * stopped at the first plugin bean declared by class, with "No default constructor found", and then at the
+ * first one with an autowired setter.
+ *
+ * Every bean definition with a class is covered, so it does not matter how a plugin declared it.
+ *
+ * The injection points of every bean are registered as well, Spring's included. An application running
+ * on generated artifacts has the processors that inject through annotations registered again, because a bean
+ * built by a supplier and declared as an interface hides the class whose members need injecting; those
+ * processors then inject every bean, including the ones the generated code already injected, and do it
+ * reflectively. Only the annotated members of Spring's beans are registered: creating them is the generated
+ * code's business.
+ *
+ * @since 9.0
+ */
+public class BeanReflectionBeanFactoryInitializationAotProcessor implements BeanFactoryInitializationAotProcessor {
+
+ private static final String SPRING_PACKAGE = "org.springframework.";
+
+ /** The annotations Spring injects a member through, or calls a method for. */
+ private static final List> INJECTION_ANNOTATIONS = List.of(
+ Autowired.class, Value.class, Inject.class, Resource.class, PostConstruct.class, PreDestroy.class);
+
+ /** Only its annotated members are reached: a Spring bean, or the product of a factory method. */
+ private static final int INJECTED = 0;
+
+ /** Also given its properties through its setters, after a supplier created it. */
+ private static final int WIRED = 1;
+
+ /** Also created through its constructor. */
+ private static final int CREATED = 2;
+
+ @Override
+ @Nullable
+ public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
+ Map, Integer> beanClasses = beanClassesOf(beanFactory);
+ if (beanClasses.isEmpty()) {
+ return null;
+ }
+ return (generationContext, beanFactoryInitializationCode) -> {
+ ReflectionHints reflection = generationContext.getRuntimeHints().reflection();
+ beanClasses.forEach((beanClass, access) -> register(reflection, beanClass, access));
+ };
+ }
+
+ /**
+ * The class of every bean, and how much of it is reached reflectively: a bean is created through its
+ * constructor unless a supplier or a factory method creates it, and the product of a factory method, like
+ * a Spring bean, only has its annotated members reached.
+ */
+ private Map, Integer> beanClassesOf(ConfigurableListableBeanFactory beanFactory) {
+ Map, Integer> beanClasses = new LinkedHashMap<>();
+ for (String name : beanFactory.getBeanDefinitionNames()) {
+ BeanDefinition definition;
+ try {
+ definition = beanFactory.getMergedBeanDefinition(name);
+ }
+ catch (NoSuchBeanDefinitionException ex) {
+ continue;
+ }
+ if (!(definition instanceof AbstractBeanDefinition beanDefinition) || beanDefinition.isAbstract()) {
+ continue;
+ }
+ Class> beanClass;
+ int access;
+ if (beanDefinition.getFactoryMethodName() != null) {
+ beanClass = productOf(beanFactory, name);
+ access = INJECTED;
+ }
+ else {
+ beanClass = beanClassOf(beanDefinition, beanFactory.getBeanClassLoader());
+ access = (beanDefinition.getInstanceSupplier() == null) ? CREATED : WIRED;
+ }
+ if (beanClass == null) {
+ continue;
+ }
+ if (beanClass.getName().startsWith(SPRING_PACKAGE)) {
+ access = INJECTED;
+ }
+ beanClasses.merge(beanClass, access, Math::max);
+ }
+ return beanClasses;
+ }
+
+ /** What a factory method creates, as far as it can be told without calling it. */
+ @Nullable
+ private static Class> productOf(ConfigurableListableBeanFactory beanFactory, String name) {
+ try {
+ return beanFactory.getType(name, false);
+ }
+ catch (RuntimeException | LinkageError ex) {
+ return null;
+ }
+ }
+
+ /**
+ * The class a definition creates, whether it holds the class or only its name: the bean DSL declares a
+ * bean by name as often as by class, and the name is resolved only when the bean is created.
+ */
+ @Nullable
+ private static Class> beanClassOf(AbstractBeanDefinition beanDefinition, @Nullable ClassLoader classLoader) {
+ if (beanDefinition.hasBeanClass()) {
+ return beanDefinition.getBeanClass();
+ }
+ String className = beanDefinition.getBeanClassName();
+ if (className == null) {
+ return null;
+ }
+ try {
+ return ClassUtils.forName(className, classLoader);
+ }
+ catch (ClassNotFoundException | LinkageError ex) {
+ return null;
+ }
+ }
+
+ private static void register(ReflectionHints reflection, Class> beanClass, int access) {
+ if (access == CREATED) {
+ reflection.registerType(beanClass, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
+ MemberCategory.INVOKE_PUBLIC_METHODS);
+ }
+ else if (access == WIRED) {
+ reflection.registerType(beanClass, MemberCategory.INVOKE_PUBLIC_METHODS);
+ }
+ try {
+ ReflectionUtils.doWithMethods(beanClass, method -> reflection.registerMethod(method, ExecutableMode.INVOKE),
+ BeanReflectionBeanFactoryInitializationAotProcessor::isInjectionPoint);
+ ReflectionUtils.doWithFields(beanClass, reflection::registerField,
+ BeanReflectionBeanFactoryInitializationAotProcessor::isInjectionPoint);
+ }
+ catch (LinkageError ex) {
+ // a member naming a class that is absent here cannot be injected here either
+ }
+ }
+
+ private static boolean isInjectionPoint(AnnotatedElement element) {
+ for (Class extends Annotation> annotation : INJECTION_ANNOTATIONS) {
+ if (AnnotatedElementUtils.hasAnnotation(element, annotation)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index 26b1f6d6e64..d7f9d8f22f8 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -20,4 +20,5 @@ org.apache.grails.core.aot.VarargsBeanRegistrationAotProcessor
org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor=\
org.apache.grails.core.aot.ApplicationBytecodeBeanFactoryInitializationAotProcessor,\
org.apache.grails.core.aot.ArtefactClassesBeanFactoryInitializationAotProcessor,\
-org.apache.grails.core.aot.ArtefactReflectionBeanFactoryInitializationAotProcessor
+org.apache.grails.core.aot.ArtefactReflectionBeanFactoryInitializationAotProcessor,\
+org.apache.grails.core.aot.BeanReflectionBeanFactoryInitializationAotProcessor
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
new file mode 100644
index 00000000000..fb55681de37
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import org.springframework.aot.generate.ClassNameGenerator
+import org.springframework.aot.generate.DefaultGenerationContext
+import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import org.springframework.beans.factory.BeanRegistrar
+import org.springframework.beans.factory.BeanRegistry
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.beans.factory.annotation.Value
+import org.springframework.beans.factory.aot.BeanFactoryInitializationCode
+import org.springframework.beans.factory.support.BeanRegistryAdapter
+import org.springframework.beans.factory.support.GenericBeanDefinition
+import org.springframework.beans.factory.support.RootBeanDefinition
+import org.springframework.context.support.GenericApplicationContext
+import org.springframework.scheduling.annotation.ProxyAsyncConfiguration
+import org.springframework.core.env.Environment
+import org.springframework.javapoet.ClassName
+import spock.lang.Specification
+
+/**
+ * Covers the beans the framework declares being creatable and wirable in an image.
+ *
+ * The plugins declare their beans as the application starts -- a registrar's are left out of the
+ * generated code and declared again, and the bean DSL's are declared again at run time -- so Spring creates
+ * and wires them reflectively, and an image built without these stopped at the first plugin bean declared
+ * by class, and then at the first with an autowired setter.
+ */
+class BeanReflectionBeanFactoryInitializationAotProcessorSpec extends Specification {
+
+ GenericApplicationContext context = new GenericApplicationContext()
+
+ void cleanup() {
+ context.close()
+ }
+
+ private void register(BeanRegistrar registrar) {
+ new BeanRegistryAdapter(context, context.beanFactory, context.environment, registrar.getClass()).register(registrar)
+ }
+
+ private RuntimeHints hints() {
+ def contribution = new BeanReflectionBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory)
+ def generation = new DefaultGenerationContext(
+ new ClassNameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
+ contribution.applyTo(generation, Mock(BeanFactoryInitializationCode))
+ generation.runtimeHints
+ }
+
+ private static boolean registered(RuntimeHints hints, Class> type, MemberCategory... categories) {
+ RuntimeHintsPredicates.reflection().onType(type).withMemberCategories(categories).test(hints)
+ }
+
+ void 'a bean a registrar declares by class can be created and given its properties'() {
+ given:
+ register(new FixtureRegistrar())
+
+ when:
+ def hints = hints()
+
+ then: 'it is created through its constructor and given its properties through its setters'
+ registered(hints, DeclaredByClassFixture, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS)
+ }
+
+ void 'a bean a registrar declares with a supplier is wired but not created reflectively'() {
+ given:
+ register(new FixtureRegistrar())
+
+ when:
+ def hints = hints()
+
+ then: 'the supplier creates it, and Spring still sets its properties afterwards'
+ registered(hints, DeclaredWithSupplierFixture, MemberCategory.INVOKE_PUBLIC_METHODS)
+ !registered(hints, DeclaredWithSupplierFixture, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)
+ }
+
+ void 'a bean declared at run time by other means is covered as well'() {
+ given: 'a bean declared by class outside any registrar, as the bean DSL declares one'
+ context.registerBean('declaredByDsl', DeclaredByClassFixture)
+
+ when:
+ def hints = hints()
+
+ then:
+ registered(hints, DeclaredByClassFixture, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS)
+ }
+
+ void 'a bean declared by the name of its class is covered too'() {
+ given: 'a definition holding only the class name, as the bean DSL often declares one'
+ context.registerBeanDefinition('byName', new GenericBeanDefinition(beanClassName: DeclaredByClassFixture.name))
+
+ when:
+ def hints = hints()
+
+ then:
+ registered(hints, DeclaredByClassFixture, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS)
+ }
+
+ void 'the members Spring injects through an annotation can be reached, however visible they are'() {
+ given:
+ context.registerBean('injected', InjectedFixture)
+
+ when:
+ def hints = hints()
+
+ then: 'the post-processor that injects them does so reflectively'
+ RuntimeHintsPredicates.reflection().onMethodInvocation(InjectedFixture, 'setEnvironment').test(hints)
+ RuntimeHintsPredicates.reflection().onFieldAccess(InjectedFixture, 'context').test(hints)
+ RuntimeHintsPredicates.reflection().onFieldAccess(InjectedFixture, 'name').test(hints)
+ }
+
+ void 'a Spring bean has only its injection points reached'() {
+ given: 'a Spring bean with an autowired method, which the processors registered again under AOT inject too'
+ context.registerBean('async', ProxyAsyncConfiguration)
+ context.registerBean('ordinary', DeclaredByClassFixture)
+
+ when:
+ def hints = hints()
+
+ then: 'the generated code creates it, so its constructors are not registered'
+ RuntimeHintsPredicates.reflection().onMethodInvocation(ProxyAsyncConfiguration, 'setConfigurers').test(hints)
+ !registered(hints, ProxyAsyncConfiguration, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)
+ }
+
+ void 'the product of a factory method has its injection points reached'() {
+ given: 'a bean a factory method creates'
+ context.registerBeanDefinition('produced', new RootBeanDefinition(FactoryFixture).tap {
+ factoryMethodName = 'create'
+ })
+
+ when:
+ def hints = hints()
+
+ then: 'it is injected after the method returns it'
+ RuntimeHintsPredicates.reflection().onFieldAccess(InjectedFixture, 'context').test(hints)
+ !registered(hints, InjectedFixture, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)
+ }
+
+ void 'a context with no beans contributes nothing'() {
+ expect:
+ new BeanReflectionBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory) == null
+ }
+
+ static class FixtureRegistrar implements BeanRegistrar {
+
+ @Override
+ void register(BeanRegistry registry, Environment environment) {
+ registry.registerBean('byClass', DeclaredByClassFixture)
+ registry.registerBean('withSupplier', DeclaredWithSupplierFixture) { BeanRegistry.Spec spec ->
+ spec.supplier { new DeclaredWithSupplierFixture() }
+ }
+ }
+ }
+
+ static class DeclaredByClassFixture {
+
+ String name
+ }
+
+ static class DeclaredWithSupplierFixture {
+
+ String name
+ }
+
+ static class FactoryFixture {
+
+ static InjectedFixture create() {
+ new InjectedFixture()
+ }
+ }
+
+ static class InjectedFixture {
+
+ @Autowired
+ private GenericApplicationContext context
+
+ @Value('${fixture.name:fixture}')
+ private String name
+
+ private Environment environment
+
+ @Autowired
+ protected void setEnvironment(Environment environment) {
+ this.environment = environment
+ }
+ }
+}
From 59458875611cf25717510f34d1f68bfde18cd3e1 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:28 -0700
Subject: [PATCH 19/39] Register the framework classes dynamic descriptors
reach
A plugin descriptor written without static compilation reads constants such
as Settings.MIME_TYPES, asks Environment.current, creates its @Slf4j logger
and calls into the bean DSL reflectively. The first descriptor declaring a
logger stopped the application before any plugin had been registered.
---
.../core/aot/GrailsApiRuntimeHints.java | 72 ++++++++++++++++++-
.../core/aot/GrailsApiRuntimeHintsSpec.groovy | 48 +++++++++++++
2 files changed, 119 insertions(+), 1 deletion(-)
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsApiRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsApiRuntimeHints.java
index 6d29d2e346a..0ecc8bb7f8d 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsApiRuntimeHints.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/GrailsApiRuntimeHints.java
@@ -19,23 +19,37 @@
package org.apache.grails.core.aot;
import org.jspecify.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
+import org.springframework.beans.factory.BeanFactory;
+import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.io.ResourceLoader;
+import org.springframework.util.ClassUtils;
import grails.config.Config;
import grails.config.ConfigMap;
+import grails.config.Settings;
import grails.core.GrailsApplication;
import grails.core.GrailsClass;
import grails.plugins.GrailsPlugin;
import grails.plugins.GrailsPluginManager;
+import grails.plugins.Plugin;
+import grails.spring.BeanBuilder;
+import grails.util.BuildSettings;
+import grails.util.GrailsMessageSourceUtils;
+import grails.util.GrailsUtil;
+import org.grails.core.io.support.GrailsFactoriesLoader;
+import org.grails.spring.RuntimeSpringConfiguration;
+import org.grails.validation.ConstraintEvalUtils;
/**
* Registers the interfaces a plugin reaches through dynamically: the framework's own, and the
@@ -57,9 +71,20 @@
* not name them either. Reading a setting from the environment stopped a Hibernate application from
* starting in exactly the way reading one from the configuration stopped every application.
*
+ * The logger is here for the same reason again. A descriptor written without static compilation
+ * that declares {@code @Slf4j} creates its logger in its static initializer by a dynamic call to
+ * {@code LoggerFactory.getLogger}, and logs through it the same way, so the first such descriptor to
+ * load stopped the application with "No signature of static method: getLogger" before any plugin had
+ * been registered.
+ *
* Only the interfaces are named. What implements them is reached through them, and registering
* the implementations would be registering most of the framework.
*
+ * The exception is the framework's own classes of constants and static helpers, which have no interface
+ * to be reached through: a descriptor or a closure written without static compilation reads
+ * {@code Settings.MIME_TYPES} or asks {@code Environment.current} the same reflective way, so their
+ * constants and methods are registered as well.
+ *
* @since 8.0
*/
public class GrailsApiRuntimeHints implements RuntimeHintsRegistrar {
@@ -78,7 +103,44 @@ public class GrailsApiRuntimeHints implements RuntimeHintsRegistrar {
PropertyResolver.class,
ApplicationContext.class,
ConfigurableApplicationContext.class,
- ResourceLoader.class
+ ResourceLoader.class,
+ // What the bean DSL hands a descriptor's closures, which ask it what is already declared
+ BeanFactory.class,
+ // How a descriptor's logger is created, and what it logs through
+ LoggerFactory.class,
+ Logger.class
+ };
+
+ /**
+ * The framework's classes of constants and static helpers that code written without static compilation
+ * reads and calls, and the base class and builders a descriptor calls into.
+ */
+ private static final Class>[] CLASSES = {
+ Settings.class,
+ BuildSettings.class,
+ grails.util.Environment.class,
+ GrailsUtil.class,
+ GrailsMessageSourceUtils.class,
+ GrailsFactoriesLoader.class,
+ ConstraintEvalUtils.class,
+ Plugin.class,
+ BeanBuilder.class,
+ RuntimeSpringConfiguration.class,
+ // What the bean DSL sets a bean's options on, and the helper a descriptor checks for optional
+ // dependencies with
+ AbstractBeanDefinition.class,
+ ClassUtils.class
+ };
+
+ /**
+ * The same, for classes this one cannot name: where a request's attributes and views are found, which is in
+ * a module this one does not depend on; and the property {@code metaClass.encodeAsHTML << { ... }} adds a
+ * method through, which Groovy declares {@code protected} and its own metadata does not cover -- the codecs
+ * add every {@code encodeAs} method that way.
+ */
+ private static final String[] CLASS_NAMES = {
+ "org.grails.web.util.GrailsApplicationAttributes",
+ "groovy.lang.ExpandoMetaClass$ExpandoMetaProperty"
};
@Override
@@ -86,5 +148,13 @@ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader)
for (Class> type : TYPES) {
hints.reflection().registerType(type, MemberCategory.INVOKE_DECLARED_METHODS);
}
+ for (Class> type : CLASSES) {
+ hints.reflection().registerType(type, MemberCategory.INVOKE_DECLARED_METHODS,
+ MemberCategory.ACCESS_PUBLIC_FIELDS);
+ }
+ for (String type : CLASS_NAMES) {
+ hints.reflection().registerTypeIfPresent(classLoader, type, MemberCategory.INVOKE_DECLARED_METHODS,
+ MemberCategory.ACCESS_PUBLIC_FIELDS);
+ }
}
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsApiRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsApiRuntimeHintsSpec.groovy
index 2326704a818..5e8f0fb22df 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsApiRuntimeHintsSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/GrailsApiRuntimeHintsSpec.groovy
@@ -23,14 +23,26 @@ import org.springframework.aot.hint.RuntimeHints
import org.springframework.aot.hint.TypeReference
import spock.lang.Specification
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import org.springframework.beans.factory.BeanFactory
+import org.springframework.beans.factory.support.AbstractBeanDefinition
import org.springframework.context.ApplicationContext
import org.springframework.core.env.Environment
import org.springframework.core.env.PropertyResolver
+import org.springframework.util.ClassUtils
import grails.config.Config
import grails.config.ConfigMap
+import grails.config.Settings
import grails.core.GrailsApplication
import grails.plugins.GrailsPluginManager
+import grails.spring.BeanBuilder
+import grails.util.BuildSettings
+import grails.util.Environment as GrailsEnvironment
+import grails.util.GrailsUtil
+import org.grails.spring.RuntimeSpringConfiguration
/**
* Covers the framework's own interfaces being callable from an image.
@@ -77,6 +89,42 @@ class GrailsApiRuntimeHintsSpec extends Specification {
invocable(ApplicationContext)
}
+ void 'a descriptor can create its logger and log through it'() {
+ given: 'the call a dynamically compiled descriptor declaring @Slf4j makes in its static initializer'
+ def getLogger = LoggerFactory.getMethod('getLogger', String)
+
+ expect: 'the first such descriptor to load stopped the application before any plugin was registered'
+ getLogger.declaringClass == LoggerFactory
+ invocable(LoggerFactory)
+ invocable(Logger)
+ }
+
+ void 'the constants and static helpers dynamically compiled code reads can be reached'() {
+ expect: 'a descriptor reads Settings.MIME_TYPES and asks Environment.current reflectively'
+ [Settings, BuildSettings, GrailsEnvironment, GrailsUtil].every {
+ def hint = hints.reflection().getTypeHint(TypeReference.of(it))
+ hint != null && hint.memberCategories.containsAll([MemberCategory.INVOKE_DECLARED_METHODS,
+ MemberCategory.ACCESS_PUBLIC_FIELDS])
+ }
+ }
+
+ void 'the builder a descriptor declares its beans with can be called'() {
+ expect: 'the bean DSL is called the same dynamic way'
+ invocable(BeanBuilder)
+ invocable(RuntimeSpringConfiguration)
+ }
+
+ void 'what a bean DSL closure calls on Spring can be called'() {
+ expect: 'a descriptor checks for an optional dependency, asks what is declared and sets a bean option dynamically'
+ [ClassUtils, BeanFactory, AbstractBeanDefinition].every { invocable(it) }
+ }
+
+ void 'a method can be added through a meta class property'() {
+ expect: 'the codecs add every encodeAs method with metaClass.encodeAsHTML << { ... }'
+ def hint = hints.reflection().getTypeHint(TypeReference.of('groovy.lang.ExpandoMetaClass$ExpandoMetaProperty'))
+ hint != null && hint.memberCategories.contains(MemberCategory.INVOKE_DECLARED_METHODS)
+ }
+
void 'the call that stopped a context from starting is covered'() {
given: 'the form a plugin uses to read a setting with a type and a default'
def getProperty = ConfigMap.getMethod('getProperty', String, Class, Object)
From 3ffaa34bd486cbe7e12b35e912b8e23f7d5006bd Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:28 -0700
Subject: [PATCH 20/39] Register the property editors the core plugin installs
Spring creates a fresh instance of each editor through its constructor for
every bean it sets properties on, so the first bean it configured failed with
"No default constructor found".
---
.../core/aot/PropertyEditorRuntimeHints.java | 56 +++++++++++++++++++
.../resources/META-INF/spring/aot.factories | 3 +-
.../aot/PropertyEditorRuntimeHintsSpec.groovy | 48 ++++++++++++++++
3 files changed, 106 insertions(+), 1 deletion(-)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/PropertyEditorRuntimeHints.java
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/PropertyEditorRuntimeHintsSpec.groovy
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/PropertyEditorRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/PropertyEditorRuntimeHints.java
new file mode 100644
index 00000000000..cc08dc3dcd3
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/PropertyEditorRuntimeHints.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+
+import org.grails.beans.support.PropertiesEditor;
+import org.grails.core.support.ClassEditor;
+
+/**
+ * Registers the property editors the core plugin installs, which Spring creates reflectively.
+ *
+ * The core plugin registers its editors by class, and Spring creates a fresh instance of each through
+ * its constructor for every bean it sets properties on, because an editor holds state. An image keeps a
+ * constructor only when something asked for it, so an image built without these could not create the
+ * first bean Spring configured, with "Failed to instantiate [PropertiesEditor]: No default constructor
+ * found".
+ *
+ * @since 9.0
+ */
+public class PropertyEditorRuntimeHints implements RuntimeHintsRegistrar {
+
+ /** The editors the core plugin registers by class. */
+ private static final Class>[] EDITORS = {
+ ClassEditor.class,
+ PropertiesEditor.class
+ };
+
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ for (Class> editor : EDITORS) {
+ hints.reflection().registerType(editor, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
+ }
+ }
+
+}
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index d7f9d8f22f8..a12939188d2 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -11,7 +11,8 @@ org.apache.grails.core.aot.GrailsClosureRuntimeHints,\
org.apache.grails.core.aot.GrailsFactoriesRuntimeHints,\
org.apache.grails.core.aot.GrailsPluginRuntimeHints,\
org.apache.grails.core.aot.GrailsResourceRuntimeHints,\
-org.apache.grails.core.aot.GroovyExtensionModuleRuntimeHints
+org.apache.grails.core.aot.GroovyExtensionModuleRuntimeHints,\
+org.apache.grails.core.aot.PropertyEditorRuntimeHints
org.springframework.beans.factory.aot.BeanRegistrationAotProcessor=\
org.apache.grails.core.aot.AutowireModeBeanRegistrationAotProcessor,\
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/PropertyEditorRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/PropertyEditorRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..8a3958a4802
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/PropertyEditorRuntimeHintsSpec.groovy
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import spock.lang.Specification
+
+import org.grails.beans.support.PropertiesEditor
+import org.grails.core.support.ClassEditor
+
+/**
+ * Covers the editors the core plugin installs being creatable in an image. Spring creates one of each
+ * through its constructor for every bean it sets properties on.
+ */
+class PropertyEditorRuntimeHintsSpec extends Specification {
+
+ RuntimeHints hints = new RuntimeHints()
+
+ void setup() {
+ new PropertyEditorRuntimeHints().registerHints(hints, getClass().classLoader)
+ }
+
+ void 'the editors the core plugin registers by class can be created'() {
+ expect: 'an image without them could not create the first bean Spring configured'
+ [ClassEditor, PropertiesEditor].every {
+ RuntimeHintsPredicates.reflection().onType(it)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+ }
+}
From 9c3dc6f3204e4f6c9747a02a5875fbfa632b2788 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:28 -0700
Subject: [PATCH 21/39] Register the JDK types dynamically compiled framework
code calls
Calls on a map, a string or a number in a descriptor's closures, the bean DSL
and the framework's older Groovy are resolved through the metaclass and made
reflectively, as are constructors and constants such as File.separator.
Groovy's own metadata covers Groovy's types, not the JDK's.
---
.../core/aot/JdkDispatchRuntimeHints.java | 111 ++++++++++++++++++
.../resources/META-INF/spring/aot.factories | 1 +
.../aot/JdkDispatchRuntimeHintsSpec.groovy | 60 ++++++++++
3 files changed, 172 insertions(+)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/JdkDispatchRuntimeHints.java
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/JdkDispatchRuntimeHintsSpec.groovy
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/JdkDispatchRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/JdkDispatchRuntimeHints.java
new file mode 100644
index 00000000000..4abe16ac4a4
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/JdkDispatchRuntimeHints.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import java.io.File;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+
+/**
+ * Registers the JDK types the framework's dynamically compiled code calls.
+ *
+ * A plugin descriptor's closures, the bean DSL and much of the framework's older Groovy are compiled
+ * without static compilation, so a call on a map, a string or a number in them is resolved through Groovy's
+ * metaclass for whatever it is made on, and made reflectively -- and so is a {@code new ArrayList()}, and
+ * so is reading a constant such as {@code File.separator}. An
+ * image keeps a JDK method or constructor for that only when something asked for it, and Groovy's own
+ * metadata covers the types Groovy owns rather than the JDK's. An image built without these stopped as the
+ * plugins declared their beans, on a call nobody wrote on a type everybody uses.
+ *
+ * The types are the ones that code calls, which are few and stable: the collections and their entries,
+ * strings, numbers and their wrappers, and the static helpers it reaches for. Where an interface declares
+ * the method, the interface is named and its implementations are reached through it.
+ *
+ * @since 9.0
+ */
+public class JdkDispatchRuntimeHints implements RuntimeHintsRegistrar {
+
+ /** What dynamically compiled code calls methods on and reads constants from. */
+ private static final Class>[] CALLED = {
+ Object.class,
+ String.class,
+ CharSequence.class,
+ Comparable.class,
+ Number.class,
+ Boolean.class,
+ Enum.class,
+ Iterable.class,
+ Iterator.class,
+ Collection.class,
+ List.class,
+ Set.class,
+ Map.class,
+ Map.Entry.class,
+ System.class,
+ Arrays.class,
+ Collections.class,
+ Objects.class,
+ File.class
+ };
+
+ /** What it creates with {@code new}. */
+ private static final Class>[] CREATED = {
+ ArrayList.class,
+ HashMap.class,
+ LinkedHashMap.class,
+ TreeMap.class,
+ HashSet.class,
+ LinkedHashSet.class,
+ TreeSet.class,
+ BigDecimal.class,
+ BigInteger.class
+ };
+
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ for (Class> type : CALLED) {
+ hints.reflection().registerType(type, MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.ACCESS_PUBLIC_FIELDS);
+ }
+ for (Class> type : CREATED) {
+ hints.reflection().registerType(type, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS);
+ }
+ }
+
+}
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index a12939188d2..3628fcb5ecc 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -12,6 +12,7 @@ org.apache.grails.core.aot.GrailsFactoriesRuntimeHints,\
org.apache.grails.core.aot.GrailsPluginRuntimeHints,\
org.apache.grails.core.aot.GrailsResourceRuntimeHints,\
org.apache.grails.core.aot.GroovyExtensionModuleRuntimeHints,\
+org.apache.grails.core.aot.JdkDispatchRuntimeHints,\
org.apache.grails.core.aot.PropertyEditorRuntimeHints
org.springframework.beans.factory.aot.BeanRegistrationAotProcessor=\
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/JdkDispatchRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/JdkDispatchRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..3c318368cbe
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/JdkDispatchRuntimeHintsSpec.groovy
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import spock.lang.Shared
+import spock.lang.Specification
+
+/**
+ * Covers the JDK types dynamically compiled framework code calls being callable in an image, where Groovy
+ * resolves each call through a metaclass and makes it reflectively.
+ */
+class JdkDispatchRuntimeHintsSpec extends Specification {
+
+ @Shared
+ RuntimeHints hints = new RuntimeHints()
+
+ void setupSpec() {
+ new JdkDispatchRuntimeHints().registerHints(hints, getClass().classLoader)
+ }
+
+ void '#type.simpleName can be called'() {
+ expect:
+ RuntimeHintsPredicates.reflection().onType(type).withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS).test(hints)
+
+ where: 'the types a descriptor or the bean DSL was seen calling methods on as an application started'
+ type << [Map, Map.Entry, String, Number, Boolean, Enum, Object, System, Collections, Arrays, Objects, File]
+ }
+
+ void 'a constant can be read'() {
+ expect: 'reading File.separator in dynamically compiled code is a reflective field read'
+ RuntimeHintsPredicates.reflection().onFieldAccess(File, 'separator').test(hints)
+ }
+
+ void '#type.simpleName can be created'() {
+ expect: 'a new in dynamically compiled code is a call Groovy resolves too'
+ RuntimeHintsPredicates.reflection().onType(type).withMemberCategories(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS).test(hints)
+
+ where:
+ type << [ArrayList, LinkedHashMap, HashSet, TreeMap, BigDecimal, BigInteger]
+ }
+}
From 0ee0dbad563c4ddded09950f093513e41f3440b5 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:29 -0700
Subject: [PATCH 22/39] Register the builder URL mappings are evaluated against
Every mapping in a URL mappings closure is a dynamic call on the builder it is
delegated to, which reads the builder's fields as well as its methods.
---
.../mapping/aot/UrlMappingRuntimeHints.java | 11 ++++
.../aot/UrlMappingRuntimeHintsSpec.groovy | 59 +++++++++++++++++++
2 files changed, 70 insertions(+)
create mode 100644 grails-web-url-mappings/src/test/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy
diff --git a/grails-web-url-mappings/src/main/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHints.java b/grails-web-url-mappings/src/main/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHints.java
index 2124937fa4b..08eade865a2 100644
--- a/grails-web-url-mappings/src/main/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHints.java
+++ b/grails-web-url-mappings/src/main/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHints.java
@@ -49,6 +49,13 @@ public class UrlMappingRuntimeHints implements RuntimeHintsRegistrar {
"grails.web.mapping.UrlMappingData"
};
+ /**
+ * What a URL mappings closure is delegated to while the mappings are evaluated. Every mapping in it is
+ * a call the closure resolves dynamically against the builder, which reads the builder's own fields as
+ * well as calling its methods.
+ */
+ private static final String MAPPINGS_BUILDER = "org.grails.web.mapping.DefaultUrlMappingEvaluator$UrlMappingBuilder";
+
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
for (String type : DISPATCHED_TYPES) {
@@ -57,5 +64,9 @@ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader)
MemberCategory.INVOKE_PUBLIC_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
+ hints.reflection().registerTypeIfPresent(classLoader, MAPPINGS_BUILDER,
+ MemberCategory.INVOKE_DECLARED_METHODS,
+ MemberCategory.INVOKE_PUBLIC_METHODS,
+ MemberCategory.ACCESS_DECLARED_FIELDS);
}
}
diff --git a/grails-web-url-mappings/src/test/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..ac709cbb0ce
--- /dev/null
+++ b/grails-web-url-mappings/src/test/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.web.mapping.aot
+
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.TypeReference
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import spock.lang.Specification
+
+import grails.web.mapping.LinkGenerator
+import grails.web.mapping.UrlMapping
+import grails.web.mapping.UrlMappingInfo
+
+/**
+ * Covers the URL mappings being evaluated and used in an image: the types Groovy dispatches on, and the
+ * builder a URL mappings closure is delegated to.
+ */
+class UrlMappingRuntimeHintsSpec extends Specification {
+
+ RuntimeHints hints = new RuntimeHints()
+
+ void setup() {
+ new UrlMappingRuntimeHints().registerHints(hints, getClass().classLoader)
+ }
+
+ void 'the types Groovy dispatches on can be called'() {
+ expect:
+ [UrlMappingInfo, UrlMapping, LinkGenerator].every {
+ RuntimeHintsPredicates.reflection().onType(it)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.INVOKE_PUBLIC_METHODS)
+ .test(hints)
+ }
+ }
+
+ void 'the builder a URL mappings closure is delegated to can be called and read'() {
+ expect: 'each mapping is a call the closure resolves against the builder, which reads its own fields too'
+ RuntimeHintsPredicates.reflection()
+ .onType(TypeReference.of('org.grails.web.mapping.DefaultUrlMappingEvaluator$UrlMappingBuilder'))
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.ACCESS_DECLARED_FIELDS)
+ .test(hints)
+ }
+}
From 6ef19da24b8b223361299d9eaed1cd1b5cd3197f Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:29 -0700
Subject: [PATCH 23/39] Register the servlet context holder Holders creates by
name
Holders cannot depend on the servlet API, so it creates the holder from its
name. Without the constructor the dispatcher servlet failed to start with a
NullPointerException.
---
.../aot/ServletContextHolderRuntimeHints.java | 46 +++++++++++++++
.../resources/META-INF/spring/aot.factories | 2 +
...ervletContextHolderRuntimeHintsSpec.groovy | 58 +++++++++++++++++++
3 files changed, 106 insertions(+)
create mode 100644 grails-web-common/src/main/groovy/org/apache/grails/web/common/aot/ServletContextHolderRuntimeHints.java
create mode 100644 grails-web-common/src/main/resources/META-INF/spring/aot.factories
create mode 100644 grails-web-common/src/test/groovy/org/apache/grails/web/common/aot/ServletContextHolderRuntimeHintsSpec.groovy
diff --git a/grails-web-common/src/main/groovy/org/apache/grails/web/common/aot/ServletContextHolderRuntimeHints.java b/grails-web-common/src/main/groovy/org/apache/grails/web/common/aot/ServletContextHolderRuntimeHints.java
new file mode 100644
index 00000000000..2c684affa02
--- /dev/null
+++ b/grails-web-common/src/main/groovy/org/apache/grails/web/common/aot/ServletContextHolderRuntimeHints.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.web.common.aot;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+
+import grails.web.context.WebRequestServletHolder;
+
+/**
+ * Registers the holder {@code Holders} keeps the servlet context in, which it creates by name.
+ *
+ * {@code Holders} is in a module that cannot depend on the servlet API, so it creates the holder
+ * reflectively from its name. An image keeps the constructor only when something asked for it, and without
+ * it the holder was never created and the dispatcher servlet failed to start, with a
+ * {@code NullPointerException} where the servlet context was handed to the holder that was not there.
+ *
+ * @since 9.0
+ */
+public class ServletContextHolderRuntimeHints implements RuntimeHintsRegistrar {
+
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ hints.reflection().registerType(WebRequestServletHolder.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
+ }
+
+}
diff --git a/grails-web-common/src/main/resources/META-INF/spring/aot.factories b/grails-web-common/src/main/resources/META-INF/spring/aot.factories
new file mode 100644
index 00000000000..b3eeaefec08
--- /dev/null
+++ b/grails-web-common/src/main/resources/META-INF/spring/aot.factories
@@ -0,0 +1,2 @@
+org.springframework.aot.hint.RuntimeHintsRegistrar=\
+org.apache.grails.web.common.aot.ServletContextHolderRuntimeHints
diff --git a/grails-web-common/src/test/groovy/org/apache/grails/web/common/aot/ServletContextHolderRuntimeHintsSpec.groovy b/grails-web-common/src/test/groovy/org/apache/grails/web/common/aot/ServletContextHolderRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..4a692334bba
--- /dev/null
+++ b/grails-web-common/src/test/groovy/org/apache/grails/web/common/aot/ServletContextHolderRuntimeHintsSpec.groovy
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.web.common.aot
+
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import spock.lang.Specification
+
+import grails.util.Holders
+import grails.web.context.WebRequestServletHolder
+
+/**
+ * Covers the holder the servlet context is kept in being creatable in an image, where {@link Holders}
+ * creates it by name.
+ */
+class ServletContextHolderRuntimeHintsSpec extends Specification {
+
+ void 'the servlet context holder can be created'() {
+ given:
+ def hints = new RuntimeHints()
+
+ when:
+ new ServletContextHolderRuntimeHints().registerHints(hints, getClass().classLoader)
+
+ then: 'without it the dispatcher servlet failed to start, handing the servlet context to a holder that was not there'
+ RuntimeHintsPredicates.reflection().onType(WebRequestServletHolder)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+
+ void 'the holder registered is the one Holders creates'() {
+ when: 'the servlet context is handed to Holders, which created its holder by name'
+ def servletContext = new Object()
+ Holders.servletContext = servletContext
+
+ then:
+ Holders.servletContext.is(servletContext)
+
+ cleanup:
+ Holders.servletContext = null
+ }
+}
From b7c06c55114884255503f499f199ab201a06f18e Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:29 -0700
Subject: [PATCH 24/39] Register the promise factories the event bus reads its
executor from
The event bus reads the executor as the promise factory's bean property, so
that events need not depend on the async module. Without the getter the event
bus, and with it the application context, could not be created.
---
grails-events/core/build.gradle | 1 +
.../PromiseFactoryExecutorRuntimeHints.java | 56 ++++++++++++++++
.../resources/META-INF/spring/aot.factories | 2 +
...miseFactoryExecutorRuntimeHintsSpec.groovy | 65 +++++++++++++++++++
4 files changed, 124 insertions(+)
create mode 100644 grails-events/core/src/main/groovy/org/apache/grails/events/aot/PromiseFactoryExecutorRuntimeHints.java
create mode 100644 grails-events/core/src/main/resources/META-INF/spring/aot.factories
create mode 100644 grails-events/core/src/test/groovy/org/apache/grails/events/aot/PromiseFactoryExecutorRuntimeHintsSpec.groovy
diff --git a/grails-events/core/build.gradle b/grails-events/core/build.gradle
index e7a09145ac6..e6ad07c2589 100644
--- a/grails-events/core/build.gradle
+++ b/grails-events/core/build.gradle
@@ -44,6 +44,7 @@ dependencies {
implementation 'org.slf4j:slf4j-api'
testImplementation 'org.spockframework:spock-core'
+ testImplementation project(':grails-async-core') // the promise factories whose executor the event bus reads
testRuntimeOnly 'org.slf4j:slf4j-nop' // Get rid of warning about missing slf4j implementation during test task
diff --git a/grails-events/core/src/main/groovy/org/apache/grails/events/aot/PromiseFactoryExecutorRuntimeHints.java b/grails-events/core/src/main/groovy/org/apache/grails/events/aot/PromiseFactoryExecutorRuntimeHints.java
new file mode 100644
index 00000000000..695713a2ed8
--- /dev/null
+++ b/grails-events/core/src/main/groovy/org/apache/grails/events/aot/PromiseFactoryExecutorRuntimeHints.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.events.aot;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+
+/**
+ * Registers the promise factories the event bus reads its executor from.
+ *
+ * The event bus runs its listeners on the executor of the application's promise factory, and reads it as
+ * the factory's {@code executor} bean property so that events need not depend on the async module. That is a
+ * reflective call to the getter, which an image keeps only when asked, so an image built without these could
+ * not create the event bus, and with it the application context.
+ *
+ * Named rather than referenced, for the same reason the property is read: the factories are in a module
+ * this one does not depend on. Each is registered only when it is present.
+ *
+ * @since 9.0
+ */
+public class PromiseFactoryExecutorRuntimeHints implements RuntimeHintsRegistrar {
+
+ /** The promise factories that expose the executor they run on. */
+ private static final String[] PROMISE_FACTORIES = {
+ "org.grails.async.factory.future.CompletableFuturePromiseFactory",
+ "org.grails.async.factory.future.VirtualThreadPromiseFactory",
+ "org.grails.async.factory.groovy.AwaitablePromiseFactory"
+ };
+
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
+ for (String promiseFactory : PROMISE_FACTORIES) {
+ hints.reflection().registerTypeIfPresent(classLoader, promiseFactory, MemberCategory.INVOKE_PUBLIC_METHODS);
+ }
+ }
+
+}
diff --git a/grails-events/core/src/main/resources/META-INF/spring/aot.factories b/grails-events/core/src/main/resources/META-INF/spring/aot.factories
new file mode 100644
index 00000000000..fe17c1e1414
--- /dev/null
+++ b/grails-events/core/src/main/resources/META-INF/spring/aot.factories
@@ -0,0 +1,2 @@
+org.springframework.aot.hint.RuntimeHintsRegistrar=\
+org.apache.grails.events.aot.PromiseFactoryExecutorRuntimeHints
diff --git a/grails-events/core/src/test/groovy/org/apache/grails/events/aot/PromiseFactoryExecutorRuntimeHintsSpec.groovy b/grails-events/core/src/test/groovy/org/apache/grails/events/aot/PromiseFactoryExecutorRuntimeHintsSpec.groovy
new file mode 100644
index 00000000000..33c34ec643c
--- /dev/null
+++ b/grails-events/core/src/test/groovy/org/apache/grails/events/aot/PromiseFactoryExecutorRuntimeHintsSpec.groovy
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.events.aot
+
+import org.springframework.aot.hint.MemberCategory
+import org.springframework.aot.hint.RuntimeHints
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import org.springframework.beans.BeanWrapperImpl
+import spock.lang.Specification
+
+import org.grails.async.factory.future.CompletableFuturePromiseFactory
+import org.grails.async.factory.future.VirtualThreadPromiseFactory
+
+/**
+ * Covers the executor the event bus runs on being readable in an image, where the event bus reads it from the
+ * promise factory as a bean property.
+ */
+class PromiseFactoryExecutorRuntimeHintsSpec extends Specification {
+
+ RuntimeHints hints = new RuntimeHints()
+
+ void setup() {
+ new PromiseFactoryExecutorRuntimeHints().registerHints(hints, getClass().classLoader)
+ }
+
+ void 'the executor of #factory.simpleName can be read'() {
+ expect: 'reading a bean property is a reflective call to its getter'
+ RuntimeHintsPredicates.reflection().onType(factory).withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS).test(hints)
+
+ where:
+ factory << [CompletableFuturePromiseFactory, VirtualThreadPromiseFactory]
+ }
+
+ void 'the property registered is the one the event bus reads'() {
+ given:
+ def promiseFactory = new CompletableFuturePromiseFactory()
+
+ expect:
+ new BeanWrapperImpl(promiseFactory).isReadableProperty('executor')
+
+ cleanup:
+ promiseFactory.close()
+ }
+
+ void 'a factory that is not on the classpath is skipped'() {
+ expect: 'the async module providing the third is not a dependency here'
+ hints.reflection().typeHints().noneMatch { it.type.name == 'org.grails.async.factory.groovy.AwaitablePromiseFactory' }
+ }
+}
From 0c63f49da736cb773a4c11a69d041720ba0458e8 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:39 -0700
Subject: [PATCH 25/39] Document what the framework registers for a native
image
Lists what an application gets without recording any metadata: the plugins,
their beans and artefacts, the reflection compiled Groovy implies, and the
resources the framework reads.
---
.../src/en/guide/deployment/deploymentAot.adoc | 13 +++++++++++++
grails-doc/src/en/guide/introduction/whatsNew.adoc | 4 +++-
2 files changed, 16 insertions(+), 1 deletion(-)
diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index 00bdee6f745..0418fc1c577 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
@@ -106,6 +106,19 @@ A native image needs every Groovy class compiled with invokedynamic. A classic c
An application that applies GraalVM's plugin compiles every Groovy class with invokedynamic. Setting `grails { indy = false }` in such an application fails the build with the reason as soon as it is evaluated, and a compile task whose `indy` compiler option is `false` when it starts, however it was set, fails the same way, rather than building an image that fails on its first dynamic call.
+==== What the framework registers for you
+
+Starting an application needs reflection the framework does on its own behalf, and an image keeps none of it unless asked. The framework asks while the code is being generated, so an image starts without anything having to be recorded first. It registers:
+
+* the plugin descriptors and the plugin classes they name, which is how the plugins are found at all;
+* the classes listed in `META-INF/grails.factories`, such as the artefact handlers;
+* the beans the plugins declare, through a `BeanRegistrar` or the bean DSL, which are declared again as the application starts and created and wired from there;
+* the artefacts the application holds -- including ones it did not write, such as the default URL mappings -- and the artefacts the plugins provide, such as the codecs;
+* what Groovy does reflectively even for statically compiled classes, in the framework and in the application's own packages: creating a Groovy enum's constants, initializing a trait from a class that implements it, and turning a closure into the interface a method takes;
+* the build information that says which environment the application was packaged for, and the default validation messages.
+
+What remains the application's is the reflection its own dynamically compiled code does. A call written without static compilation is resolved where it is made, against whatever it is made on, and only a run shows what that is. Compile such code statically, as a generated application's `Application` class is, or record what it does as described below.
+
==== Recording reflection for a native image
Some of that metadata is written for you. The build reads its own output — the compiled artefacts, and the manifest naming each compiled page — and registers them, so a controller, a domain class or a GSP survives into an image without anything having to run.
diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc
index ffa222a5c35..01adb7712c0 100644
--- a/grails-doc/src/en/guide/introduction/whatsNew.adoc
+++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc
@@ -620,7 +620,9 @@ java -Dspring.aot.enabled=true -jar build/libs/myapp.jar
AOT processing is also what a GraalVM native image requires: Spring Boot refuses to start an image without a
build-time generated initializer. Reachability metadata for the application's own artefacts and compiled pages is
-written from the build output, and `traceNativeMetadata` records what the framework reflects on along a request path.
+written from the build output, the framework registers the reflection it does on its own behalf while the
+application starts -- finding the plugins, creating their beans and artefacts, and what Groovy does for enums,
+traits and closures -- and `traceNativeMetadata` records what the framework reflects on along a request path.
See the <> section for what it changes at runtime and what it
does not yet cover.
From a76c166dbde7bf58179de0fdb51ade9d21f3a2b6 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 21:58:39 -0700
Subject: [PATCH 26/39] Say the native half of native-i18n needs no recorded
metadata
The image is built from what the framework registers and the hints derived
from the configured base names, so a failure is a gap in the framework.
---
end-to-end/README.md | 9 +++++++--
.../init/nativei18n/Application.groovy | 17 +++++++++++------
2 files changed, 18 insertions(+), 8 deletions(-)
diff --git a/end-to-end/README.md b/end-to-end/README.md
index b0fc27e1e62..0c956b2dffa 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -68,8 +68,8 @@ first is covered by Spring Boot's own hints, which register the two hardcoded pa
| Bundle | Base name | Why it is here |
|---|---|---|
| the application's own | `messages` | The case Boot already covers, as a control. |
-| the plugin's | `native-messages` | Namespaced, so Boot's patterns never reach it. The plugin name is multi-word, so this also covers the descriptor's hyphenated spelling being matched against the plugin's camel-case one. |
-| one the application configured | `config.i18n.custom` | Outside `grails-app/i18n`, and written dotted, so it also proves the base name is converted to `config/i18n/custom` before being registered. |
+| the plugin's | `native-messages` | Namespaced, so Boot's patterns never reach it. Its file is at the root of the classpath, where Grails registers every properties file, so in an image this proves the plugin is found and its base name reaches the message source. The plugin name is multi-word, so this also covers the descriptor's hyphenated spelling being matched against the plugin's camel-case one. |
+| one the application configured | `config.i18n.custom` | Outside `grails-app/i18n` and the root, so the only one carried into an image by the hints derived from the base names alone, and written dotted, so it also proves the base name is converted to `config/i18n/custom` before being registered. |
Each is resolved in English and in a locale variant. The locale half is the assertion that would
fail if the hints registered *bundles* rather than resource *patterns* and the image were built with
@@ -86,6 +86,11 @@ The JVM half runs in `check` and needs nothing special. It cannot falsify a hint
fixture guard, keeping the bundles and the assertions from drifting apart. The native half is opt-in
because it needs a GraalVM toolchain and minutes of CPU.
+The native half needs no recorded metadata. Nothing traced by an agent is checked in or generated: the
+image is built from what the framework registers while the code is generated -- finding the plugins,
+creating their beans and artefacts, what Groovy does reflectively -- and from the hints derived from the
+configured base names. So a failure here is a gap in the framework, not in this fixture.
+
### Why this runs here and not on 8.0.x
Dynamic Groovy in a native image needs two things this branch has and 8.0.x deliberately does not:
diff --git a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
index b23143e59ba..483b7b69ea3 100644
--- a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
+++ b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
@@ -42,7 +42,10 @@ import org.springframework.context.MessageSource
*
* Only the first of the three is covered by Spring Boot's own hints, which register the two
* hardcoded patterns {@code messages.properties} and {@code messages_*.properties} and derive
- * nothing from the configured base names.
+ * nothing from the configured base names. Grails registers every properties file at the root of the
+ * classpath as well, which is where an application's and a plugin's bundles land, so of the three
+ * only the configured base name, which is not at the root, is carried into an image by the hints
+ * derived from {@code spring.messages.basename} alone.
*
* Compiled statically, as a generated application's {@code Application} class is, so that the
* image depends on resource hints for what this checks and not on reflection metadata for how it
@@ -66,13 +69,15 @@ class Application extends GrailsAutoConfiguration {
check(messages, 'native.app.greeting', Locale.ENGLISH, 'hello from the application bundle')
// A plugin's bundle, base name 'native-messages'. Namespaced, so Boot's messages*
- // patterns never reach it; it survives only because the base names are recorded at build
- // time and hinted from them. The plugin name is also multi-word, so this covers the
- // descriptor's hyphenated spelling being matched against the plugin's camel-case one.
+ // patterns never reach it. Its file is at the root, which Grails registers, so what this
+ // proves in an image is that the plugin is found and its base name reaches the message
+ // source. The plugin name is also multi-word, so this covers the descriptor's hyphenated
+ // spelling being matched against the plugin's camel-case one.
check(messages, 'native.plugin.greeting', Locale.ENGLISH, 'hello from the plugin bundle')
- // A base name the application configured itself, written in dotted form, so this proves
- // config.i18n.custom was converted to config/i18n/custom before being used.
+ // A base name the application configured itself, outside the root and written in dotted
+ // form. The one bundle only the hints derived from the base names carry into an image,
+ // so this proves config.i18n.custom was converted to config/i18n/custom and registered.
check(messages, 'native.custom.greeting', Locale.ENGLISH, 'hello from a configured base name')
// A locale variant of each. In an image this is what would fail if the hints registered
From 7f3c3d5543cbb7f4049c7109969a7811b85895a6 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 22:09:41 -0700
Subject: [PATCH 27/39] Find each plugin's own configuration in a native image
A plugin's plugin.yml is read relative to the root its class was loaded
from, its JAR or its build directory. A native image has no such roots:
every class in it is at the same root, so every plugin looked for the same
/plugin.yml, which the image did not carry, and every plugin's
configuration was lost.
While the code is generated, and the roots still exist, each loaded
plugin's configuration is now copied to
META-INF/grails/plugin-configuration//, keeping its file name,
and registered as a resource. PluginUtils.readPluginConfiguration prefers
that copy to the class-relative lookup.
---
...BeanFactoryInitializationAotProcessor.java | 84 +++++++++
.../grails/core/plugins/PluginUtils.java | 45 +++++
.../resources/META-INF/spring/aot.factories | 3 +-
...ctoryInitializationAotProcessorSpec.groovy | 4 +
...ctoryInitializationAotProcessorSpec.groovy | 159 ++++++++++++++++++
.../core/plugins/PluginClassFixtures.groovy | 66 ++++++++
.../core/plugins/PluginUtilsSpec.groovy | 55 ++++++
.../en/guide/deployment/deploymentAot.adoc | 1 +
8 files changed, 416 insertions(+), 1 deletion(-)
create mode 100644 grails-core/src/main/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessor.java
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessorSpec.groovy
create mode 100644 grails-core/src/test/groovy/org/apache/grails/core/plugins/PluginClassFixtures.groovy
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessor.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessor.java
new file mode 100644
index 00000000000..7f8d5183063
--- /dev/null
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessor.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.jspecify.annotations.Nullable;
+
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.core.io.Resource;
+
+import grails.plugins.GrailsPlugin;
+import grails.plugins.GrailsPluginManager;
+import org.apache.grails.core.plugins.PluginUtils;
+
+/**
+ * Copies each plugin's configuration to a location of its own, where an application running on generated
+ * code finds it.
+ *
+ * A plugin's {@code plugin.yml} is found relative to the root its class was loaded from: the plugin's
+ * JAR, or its build directory. A native image has no such roots. Every class in it is at the same root, so
+ * every plugin's configuration is looked for at the same {@code /plugin.yml}, which is either missing or
+ * one plugin's file answering for all of them. An image built without these lost every plugin's
+ * configuration.
+ *
+ * The configurations are read from the plugins the application loaded, while the code is generated and
+ * the roots still exist, and each is written under the name of its plugin class at
+ * {@link PluginUtils#getGeneratedConfigurationPath(String, String)}, which the lookup prefers, and
+ * registered as a resource.
+ *
+ * @since 9.0
+ */
+public class PluginConfigurationBeanFactoryInitializationAotProcessor implements BeanFactoryInitializationAotProcessor {
+
+ @Override
+ @Nullable
+ public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
+ Map configurations = configurationsOf(beanFactory);
+ if (configurations.isEmpty()) {
+ return null;
+ }
+ return (generationContext, beanFactoryInitializationCode) -> configurations.forEach((path, configuration) -> {
+ generationContext.getGeneratedFiles().addResourceFile(path, configuration);
+ generationContext.getRuntimeHints().resources().registerPattern(path);
+ });
+ }
+
+ /** Where each loaded plugin's configuration is copied to, and the configuration itself. */
+ private static Map configurationsOf(ConfigurableListableBeanFactory beanFactory) {
+ Map configurations = new LinkedHashMap<>();
+ if (!(beanFactory.getSingleton(GrailsPluginManager.BEAN_NAME) instanceof GrailsPluginManager pluginManager)) {
+ return configurations;
+ }
+ for (GrailsPlugin plugin : pluginManager.getAllPlugins()) {
+ Class> pluginClass = plugin.getPluginClass();
+ Resource configuration = PluginUtils.readPluginConfiguration(pluginClass);
+ if (configuration != null) {
+ configurations.put(PluginUtils.getGeneratedConfigurationPath(pluginClass.getName(),
+ configuration.getFilename()), configuration);
+ }
+ }
+ return configurations;
+ }
+
+}
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/plugins/PluginUtils.java b/grails-core/src/main/groovy/org/apache/grails/core/plugins/PluginUtils.java
index 83d618feab0..bab393d27c6 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/plugins/PluginUtils.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/plugins/PluginUtils.java
@@ -112,6 +112,15 @@ public final class PluginUtils {
*/
public static final String PLUGIN_YML_CONFIG_PATH = "/" + PLUGIN_YML_CONFIG;
+ /**
+ * Where the build keeps a copy of each plugin's configuration for an application running on code
+ * generated ahead of time, in a directory named after the plugin class.
+ *
+ * @since 9.0
+ * @see #getGeneratedConfigurationPath(String, String)
+ */
+ public static final String GENERATED_CONFIG_PATH = "META-INF/grails/plugin-configuration/";
+
/**
* The naming suffix required for Grails plugin implementation classes.
*/
@@ -516,10 +525,19 @@ public static PluginDependencies evaluatePluginDependencies(BeanWrapper beanWrap
* The lookup probes for both {@code plugin.yml} and {@code plugin.groovy}. If both exist, a
* {@link RuntimeException} is thrown because a plugin may define only one configuration source.
*
+ * A copy the build made while generating code ahead of time is preferred, when there is one. A native
+ * image has no class roots: every class in it is at the same root, so every plugin's {@code plugin.yml}
+ * would be looked for at the same path, and the copy is the only place a plugin's own is found.
+ *
* @param pluginClass the plugin class to resolve relative to
* @return the configuration resource, or {@code null} if no config file is present
+ * @see #getGeneratedConfigurationPath(String, String)
*/
public static Resource readPluginConfiguration(Class> pluginClass) {
+ Resource generatedResource = findGeneratedConfiguration(pluginClass);
+ if (generatedResource != null) {
+ return generatedResource;
+ }
var ymlResource = getConfigurationResource(pluginClass, PLUGIN_YML_CONFIG_PATH);
var groovyResource = getConfigurationResource(pluginClass, PLUGIN_GROOVY_CONFIG_PATH);
@@ -538,6 +556,33 @@ public static Resource readPluginConfiguration(Class> pluginClass) {
return null;
}
+ /**
+ * The classpath location of the copy the build makes of a plugin's configuration while generating code
+ * ahead of time, which {@link #readPluginConfiguration(Class)} prefers to the original.
+ *
+ * @param pluginClassName the fully qualified name of the plugin class
+ * @param configFileName the name of the configuration file, {@code plugin.yml} or {@code plugin.groovy}
+ * @return the location of the copy, relative to the root of the classpath
+ * @since 9.0
+ */
+ public static String getGeneratedConfigurationPath(String pluginClassName, String configFileName) {
+ return GENERATED_CONFIG_PATH + pluginClassName + "/" + configFileName;
+ }
+
+ private static Resource findGeneratedConfiguration(Class> pluginClass) {
+ ClassLoader classLoader = pluginClass.getClassLoader();
+ if (classLoader == null) {
+ return null;
+ }
+ for (String configFileName : List.of(PLUGIN_YML_CONFIG, PLUGIN_GROOVY_CONFIG)) {
+ URL generated = classLoader.getResource(getGeneratedConfigurationPath(pluginClass.getName(), configFileName));
+ if (generated != null) {
+ return new UrlResource(generated);
+ }
+ }
+ return null;
+ }
+
/**
* Finds a plugin configuration resource at the given path relative to the
* plugin class, delegating to
diff --git a/grails-core/src/main/resources/META-INF/spring/aot.factories b/grails-core/src/main/resources/META-INF/spring/aot.factories
index 3628fcb5ecc..0bcb8b6cdf7 100644
--- a/grails-core/src/main/resources/META-INF/spring/aot.factories
+++ b/grails-core/src/main/resources/META-INF/spring/aot.factories
@@ -23,4 +23,5 @@ org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor=\
org.apache.grails.core.aot.ApplicationBytecodeBeanFactoryInitializationAotProcessor,\
org.apache.grails.core.aot.ArtefactClassesBeanFactoryInitializationAotProcessor,\
org.apache.grails.core.aot.ArtefactReflectionBeanFactoryInitializationAotProcessor,\
-org.apache.grails.core.aot.BeanReflectionBeanFactoryInitializationAotProcessor
+org.apache.grails.core.aot.BeanReflectionBeanFactoryInitializationAotProcessor,\
+org.apache.grails.core.aot.PluginConfigurationBeanFactoryInitializationAotProcessor
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy
index 861746179e8..2dc463e03f2 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy
@@ -123,6 +123,7 @@ class ArtefactClassesBeanFactoryInitializationAotProcessorSpec extends Specifica
context.beanFactory.registerSingleton(GrailsPluginManager.BEAN_NAME,
Stub(GrailsPluginManager) {
getAllPlugins() >> ([Stub(GrailsPlugin) {
+ getPluginClass() >> DemoGrailsPlugin
getProvidedArtefacts() >> ([DemoService] as Class[])
}] as GrailsPlugin[])
})
@@ -158,6 +159,9 @@ class ArtefactClassesBeanFactoryInitializationAotProcessorSpec extends Specifica
static class DemoController {
}
+ static class DemoGrailsPlugin {
+ }
+
static class DemoService {
}
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessorSpec.groovy
new file mode 100644
index 00000000000..f9b42c5f510
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessorSpec.groovy
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.aot
+
+import java.nio.file.Path
+
+import org.springframework.aot.generate.ClassNameGenerator
+import org.springframework.aot.generate.DefaultGenerationContext
+import org.springframework.aot.generate.GeneratedFiles.Kind
+import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
+import org.springframework.beans.factory.aot.BeanFactoryInitializationCode
+import org.springframework.context.support.GenericApplicationContext
+import org.springframework.javapoet.ClassName
+import spock.lang.Specification
+import spock.lang.TempDir
+
+import grails.plugins.GrailsPlugin
+import grails.plugins.GrailsPluginManager
+import org.apache.grails.core.plugins.PluginClassFixtures
+import org.apache.grails.core.plugins.PluginUtils
+
+/**
+ * Covers each plugin's configuration reaching an application running on generated code, where every class is
+ * at the same root and a plugin's {@code plugin.yml} cannot be found relative to its class.
+ *
+ * An image built without these lost every plugin's configuration.
+ */
+class PluginConfigurationBeanFactoryInitializationAotProcessorSpec extends Specification {
+
+ @TempDir
+ Path temp
+
+ GenericApplicationContext context = new GenericApplicationContext()
+
+ List loaders = []
+
+ void cleanup() {
+ context.close()
+ loaders*.close()
+ }
+
+ /** A plugin class in a root of its own, as each plugin's JAR is, with the configuration given, if any. */
+ private Class> plugin(String className, String configFileName = null, String configuration = null) {
+ Path root = temp.resolve(className)
+ PluginClassFixtures.compilePlugin(root, className)
+ if (configFileName) {
+ PluginClassFixtures.write(root, configFileName, configuration)
+ }
+ URLClassLoader loader = PluginClassFixtures.loaderOver(root)
+ loaders << loader
+ loader.loadClass(className)
+ }
+
+ private void loaded(Class>... pluginClasses) {
+ GrailsPlugin[] plugins = pluginClasses.collect { Class> pluginClass ->
+ Stub(GrailsPlugin) {
+ getPluginClass() >> pluginClass
+ }
+ } as GrailsPlugin[]
+ context.beanFactory.registerSingleton(GrailsPluginManager.BEAN_NAME, Stub(GrailsPluginManager) {
+ getAllPlugins() >> plugins
+ })
+ }
+
+ private DefaultGenerationContext generate() {
+ def generation = new DefaultGenerationContext(
+ new ClassNameGenerator(ClassName.get('com.example', 'Configuration')), new InMemoryGeneratedFiles())
+ new PluginConfigurationBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory)
+ .applyTo(generation, Mock(BeanFactoryInitializationCode))
+ generation
+ }
+
+ private static String generated(DefaultGenerationContext generation, String path) {
+ ((InMemoryGeneratedFiles) generation.generatedFiles).getGeneratedFileContent(Kind.RESOURCE, path)
+ }
+
+ void 'each plugin configuration is copied under the name of its plugin class'() {
+ given: 'two plugins with a plugin.yml each, at the same path in their own roots'
+ loaded(plugin('fixture.alpha.AlphaGrailsPlugin', 'plugin.yml', 'alpha: one'),
+ plugin('fixture.beta.BetaGrailsPlugin', 'plugin.yml', 'beta: two'))
+ String alpha = PluginUtils.getGeneratedConfigurationPath('fixture.alpha.AlphaGrailsPlugin', 'plugin.yml')
+ String beta = PluginUtils.getGeneratedConfigurationPath('fixture.beta.BetaGrailsPlugin', 'plugin.yml')
+
+ when:
+ def generation = generate()
+
+ then: 'each is written where only its own plugin looks for it'
+ generated(generation, alpha) == 'alpha: one'
+ generated(generation, beta) == 'beta: two'
+
+ and: 'carried into an image'
+ RuntimeHintsPredicates.resource().forResource(alpha).test(generation.runtimeHints)
+ RuntimeHintsPredicates.resource().forResource(beta).test(generation.runtimeHints)
+ }
+
+ void 'a configuration written as Groovy keeps its name'() {
+ given:
+ loaded(plugin('fixture.groovy.ScriptedGrailsPlugin', 'plugin.groovy', 'scripted = true'))
+
+ expect: 'the name is how its format is chosen'
+ generated(generate(),
+ PluginUtils.getGeneratedConfigurationPath('fixture.groovy.ScriptedGrailsPlugin', 'plugin.groovy')) ==
+ 'scripted = true'
+ }
+
+ void 'where every class is at one root each plugin still finds its own configuration'() {
+ given: 'two configured plugins and one without configuration, copied while the roots still exist'
+ loaded(plugin('fixture.alpha.AlphaGrailsPlugin', 'plugin.yml', 'alpha: one'),
+ plugin('fixture.beta.BetaGrailsPlugin', 'plugin.yml', 'beta: two'),
+ plugin('fixture.gamma.GammaGrailsPlugin'))
+ def generation = generate()
+
+ and: 'an image of them: their classes and the copies at a single root, and neither plugin.yml'
+ Path image = temp.resolve('image')
+ ['fixture.alpha.AlphaGrailsPlugin', 'fixture.beta.BetaGrailsPlugin', 'fixture.gamma.GammaGrailsPlugin'].each {
+ PluginClassFixtures.compilePlugin(image, it)
+ }
+ ((InMemoryGeneratedFiles) generation.generatedFiles).getGeneratedFiles(Kind.RESOURCE).each { path, content ->
+ PluginClassFixtures.write(image, path, content.inputStream.text)
+ }
+ URLClassLoader loader = PluginClassFixtures.loaderOver(image)
+ loaders << loader
+
+ expect:
+ PluginUtils.readPluginConfiguration(loader.loadClass('fixture.alpha.AlphaGrailsPlugin')).inputStream.text == 'alpha: one'
+ PluginUtils.readPluginConfiguration(loader.loadClass('fixture.beta.BetaGrailsPlugin')).inputStream.text == 'beta: two'
+ PluginUtils.readPluginConfiguration(loader.loadClass('fixture.gamma.GammaGrailsPlugin')) == null
+ }
+
+ void 'plugins without configuration contribute nothing'() {
+ given:
+ loaded(plugin('fixture.gamma.GammaGrailsPlugin'))
+
+ expect:
+ new PluginConfigurationBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory) == null
+ }
+
+ void 'a context that is not a Grails application contributes nothing'() {
+ expect: 'a plain Spring application being generated has no plugins to ask'
+ new PluginConfigurationBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory) == null
+ }
+}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/plugins/PluginClassFixtures.groovy b/grails-core/src/test/groovy/org/apache/grails/core/plugins/PluginClassFixtures.groovy
new file mode 100644
index 00000000000..c648027ddfc
--- /dev/null
+++ b/grails-core/src/test/groovy/org/apache/grails/core/plugins/PluginClassFixtures.groovy
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.grails.core.plugins
+
+import java.nio.file.Files
+import java.nio.file.Path
+
+import groovy.transform.CompileStatic
+
+import org.codehaus.groovy.control.CompilationUnit
+import org.codehaus.groovy.control.CompilerConfiguration
+
+/**
+ * Plugin classes compiled into a directory of their own, laid out as a plugin's build lays them out, so that
+ * what is found relative to a plugin class can be arranged per test.
+ */
+@CompileStatic
+class PluginClassFixtures {
+
+ /**
+ * Compiles a plugin class with the given name into {@code root}.
+ */
+ static void compilePlugin(Path root, String className) {
+ int dot = className.lastIndexOf('.')
+ String simpleName = className.substring(dot + 1)
+ CompilerConfiguration configuration = new CompilerConfiguration()
+ configuration.targetDirectory = root.toFile()
+ CompilationUnit unit = new CompilationUnit(configuration)
+ unit.addSource("${simpleName}.groovy",
+ "package ${className.substring(0, dot)}\nclass ${simpleName} {\n def version = '1.0'\n}\n")
+ unit.compile()
+ }
+
+ /**
+ * Writes {@code content} to {@code path} under {@code root}, creating the directories it needs.
+ */
+ static void write(Path root, String path, String content) {
+ Path file = root.resolve(path)
+ Files.createDirectories(file.parent)
+ Files.writeString(file, content)
+ }
+
+ /**
+ * A class loader over {@code roots} whose classes are loaded from them, the plugin classes included.
+ */
+ static URLClassLoader loaderOver(Path... roots) {
+ new URLClassLoader(roots.collect { Path root -> root.toUri().toURL() } as URL[],
+ PluginClassFixtures.classLoader)
+ }
+}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/plugins/PluginUtilsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/plugins/PluginUtilsSpec.groovy
index ff9359b3e60..60c4363e11e 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/plugins/PluginUtilsSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/plugins/PluginUtilsSpec.groovy
@@ -18,7 +18,10 @@
*/
package org.apache.grails.core.plugins
+import java.nio.file.Path
+
import spock.lang.Specification
+import spock.lang.TempDir
import spock.lang.Unroll
import org.grails.plugins.DefaultGrailsPlugin
@@ -28,6 +31,9 @@ import org.grails.plugins.DefaultGrailsPlugin
*/
class PluginUtilsSpec extends Specification {
+ @TempDir
+ Path temp
+
@Unroll
def "isPluginVersionCompatible checks that plugin with grailsVersion=#pluginGrailsVersion is compatible with grails #grailsVersion"() {
expect:
@@ -176,6 +182,55 @@ class PluginUtilsSpec extends Specification {
!resource.exists()
}
+ def "getGeneratedConfigurationPath names the copy after the plugin class"() {
+ expect:
+ PluginUtils.getGeneratedConfigurationPath('com.example.FooGrailsPlugin', 'plugin.yml') ==
+ 'META-INF/grails/plugin-configuration/com.example.FooGrailsPlugin/plugin.yml'
+ }
+
+ @Unroll
+ def "readPluginConfiguration prefers the generated copy of a #fileName to the one beside the plugin"(String fileName) {
+ given: 'a plugin with its configuration at its root, and a copy the build generated'
+ Path root = temp.resolve('plugin')
+ PluginClassFixtures.compilePlugin(root, 'fixture.copy.CopiedGrailsPlugin')
+ PluginClassFixtures.write(root, fileName, 'beside: the plugin')
+ PluginClassFixtures.write(root,
+ PluginUtils.getGeneratedConfigurationPath('fixture.copy.CopiedGrailsPlugin', fileName), 'copied: by the build')
+ URLClassLoader loader = PluginClassFixtures.loaderOver(root)
+
+ when:
+ def resource = PluginUtils.readPluginConfiguration(loader.loadClass('fixture.copy.CopiedGrailsPlugin'))
+
+ then: 'it keeps its name, which is how its format is chosen'
+ resource.filename == fileName
+ resource.inputStream.text == 'copied: by the build'
+
+ cleanup:
+ loader?.close()
+
+ where:
+ fileName << ['plugin.yml', 'plugin.groovy']
+ }
+
+ def "readPluginConfiguration finds each plugin's own configuration where every class is at one root"() {
+ given: 'two plugins at one root, as every class is in a native image, each with only a copy of its configuration'
+ Path root = temp.resolve('image')
+ PluginClassFixtures.compilePlugin(root, 'fixture.alpha.AlphaGrailsPlugin')
+ PluginClassFixtures.compilePlugin(root, 'fixture.beta.BetaGrailsPlugin')
+ PluginClassFixtures.write(root,
+ PluginUtils.getGeneratedConfigurationPath('fixture.alpha.AlphaGrailsPlugin', 'plugin.yml'), 'alpha: one')
+ PluginClassFixtures.write(root,
+ PluginUtils.getGeneratedConfigurationPath('fixture.beta.BetaGrailsPlugin', 'plugin.yml'), 'beta: two')
+ URLClassLoader loader = PluginClassFixtures.loaderOver(root)
+
+ expect:
+ PluginUtils.readPluginConfiguration(loader.loadClass('fixture.alpha.AlphaGrailsPlugin')).inputStream.text == 'alpha: one'
+ PluginUtils.readPluginConfiguration(loader.loadClass('fixture.beta.BetaGrailsPlugin')).inputStream.text == 'beta: two'
+
+ cleanup:
+ loader?.close()
+ }
+
// Tests for additional public methods
@Unroll
diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index 0418fc1c577..e49881e7872 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
@@ -111,6 +111,7 @@ An application that applies GraalVM's plugin compiles every Groovy class with in
Starting an application needs reflection the framework does on its own behalf, and an image keeps none of it unless asked. The framework asks while the code is being generated, so an image starts without anything having to be recorded first. It registers:
* the plugin descriptors and the plugin classes they name, which is how the plugins are found at all;
+* each plugin's own configuration, its `plugin.yml`, which is otherwise read from beside the plugin's classes, in its JAR -- and an image has no JARs, so it is copied under the plugin's name while the code is generated;
* the classes listed in `META-INF/grails.factories`, such as the artefact handlers;
* the beans the plugins declare, through a `BeanRegistrar` or the bean DSL, which are declared again as the application starts and created and wired from there;
* the artefacts the application holds -- including ones it did not write, such as the default URL mappings -- and the artefacts the plugins provide, such as the codecs;
From fbcea50afa6b588262fa56e5e4cefa4c4e77c4ea Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 22:09:41 -0700
Subject: [PATCH 28/39] Read the plugin's configuration in native-i18n
The plugin now ships a plugin.yml, and the application fails unless a value
from it reached the environment. Nothing else checks that a plugin's
configuration reaches an image, and this image is built anyway.
---
end-to-end/README.md | 7 +++++-
.../grails-app/conf/plugin.yml | 23 +++++++++++++++++++
.../init/nativei18n/Application.groovy | 15 +++++++++++-
3 files changed, 43 insertions(+), 2 deletions(-)
create mode 100644 end-to-end/native-i18n-plugin/grails-app/conf/plugin.yml
diff --git a/end-to-end/README.md b/end-to-end/README.md
index 0c956b2dffa..eb58979ed95 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -38,7 +38,7 @@ applications at via `GRAILS_REPO_URL`.
| `legacy-commands-plugin` | A Grails 8 plugin whose legacy commands are recompiled under Groovy 5. |
| `legacy-commands` | A Grails 8 application that consumes both and runs their commands through the registry. |
| `native-i18n` | An application that resolves messages from three kinds of bundle, on a JVM always and inside a GraalVM binary when asked. |
-| `native-i18n-plugin` | A plugin shipping a namespaced message bundle (`native-messages.properties`), with a multi-word plugin name. |
+| `native-i18n-plugin` | A plugin shipping a namespaced message bundle (`native-messages.properties`) and a `plugin.yml`, with a multi-word plugin name. |
| `spring-dependency-management` | A Grails 8 application that manages its versions with the legacy `io.spring.dependency-management` plugin instead of the Grails Gradle plugin's native `platform(grails-bom)`, as an upgraded Grails 7 application does. |
| `taglib-index-incremental` | Builds a Grails 8 application **twice, without a clean**, to prove a renamed or deleted tag library cannot survive in the published tag library index. Incremental behaviour is the whole point, so it cannot be expressed by a project the core build builds once for itself. |
@@ -76,6 +76,11 @@ fail if the hints registered *bundles* rather than resource *patterns* and the i
a narrower locale set than the bundles cover — the open question recorded in
https://github.com/apache/grails-core/issues/16176.
+It also reads a value from the plugin's `plugin.yml`, because the image is built anyway and nothing
+else checks that a plugin's configuration reaches one. On a JVM the file is found beside the plugin's
+classes, in its JAR; an image has no JARs, so there it is found only through the copy the build makes
+of it under the plugin's name.
+
```bash
cd end-to-end
./gradlew :native-i18n:check # the JVM half, part of `check`
diff --git a/end-to-end/native-i18n-plugin/grails-app/conf/plugin.yml b/end-to-end/native-i18n-plugin/grails-app/conf/plugin.yml
new file mode 100644
index 00000000000..35eb284e73a
--- /dev/null
+++ b/end-to-end/native-i18n-plugin/grails-app/conf/plugin.yml
@@ -0,0 +1,23 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# Found beside the plugin's classes on a JVM. An image has no such place, so the application reading this
+# proves the copy the build makes of it, under the plugin's name, was carried into the image.
+native:
+ plugin:
+ configuration: from the plugin configuration
diff --git a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
index 483b7b69ea3..e8cf7906151 100644
--- a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
+++ b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
@@ -47,6 +47,9 @@ import org.springframework.context.MessageSource
* only the configured base name, which is not at the root, is carried into an image by the hints
* derived from {@code spring.messages.basename} alone.
*
+ * It also reads a value from the plugin's {@code plugin.yml}, which on a JVM is found beside the plugin's
+ * classes and in an image only through the copy the build makes of it under the plugin's name.
+ *
* Compiled statically, as a generated application's {@code Application} class is, so that the
* image depends on resource hints for what this checks and not on reflection metadata for how it
* checks it.
@@ -95,7 +98,17 @@ class Application extends GrailsAutoConfiguration {
"the message source; an unknown code gave '${unknown}'")
}
- println 'i18n-check: every message bundle resolved'
+ // Not a bundle, but the plugin's own configuration, read from its plugin.yml. Here because the
+ // image is built anyway: on a JVM the file is found beside the plugin's classes, in its JAR, and
+ // an image has no JARs, so in one this proves the copy the build makes under the plugin's name
+ // was carried into it.
+ String configured = context.environment.getProperty('native.plugin.configuration')
+ if (configured != 'from the plugin configuration') {
+ throw new IllegalStateException("The plugin's plugin.yml did not reach the environment; " +
+ "native.plugin.configuration was '${configured}'")
+ }
+
+ println 'i18n-check: every message bundle resolved, and the plugin configuration was read'
}
catch (Throwable failure) {
failure.printStackTrace()
From 2e11f691ed2428c63850447ce0cfb0b07436e96a Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Fri, 16 Oct 2026 22:09:41 -0700
Subject: [PATCH 29/39] Scan the native-i18n plugin's dependencies
The application that consumes it applies the vulnerability scan, and so does
legacy-commands-plugin, the other plugin in this build.
---
end-to-end/native-i18n-plugin/build.gradle | 1 +
1 file changed, 1 insertion(+)
diff --git a/end-to-end/native-i18n-plugin/build.gradle b/end-to-end/native-i18n-plugin/build.gradle
index cc46af6e7b6..39b7e6c8981 100644
--- a/end-to-end/native-i18n-plugin/build.gradle
+++ b/end-to-end/native-i18n-plugin/build.gradle
@@ -21,6 +21,7 @@ plugins {
id 'org.apache.grails.buildsrc.properties'
id 'org.apache.grails.buildsrc.dependency-validator'
id 'org.apache.grails.buildsrc.compile'
+ id 'org.apache.grails.buildsrc.vulnerability-scan'
id 'org.apache.grails.gradle.grails-plugin'
}
From 919b350db22d133a76c83ed1793499c05bdb8389 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Wed, 21 Oct 2026 08:58:26 -0600
Subject: [PATCH 30/39] Run the JVM half of native-i18n in production as well
as development
The Grails Gradle plugin starts every JavaExec in development, so the JVM
half started differently from the image, which starts in production from
the build information packaged into it. It now runs in production, and once
more in development, where bundles stopped resolving until #16179 and where
this run found it.
Each run, the image's included, is told which environment to expect through
i18n.check.environment and fails in any other, so a run that silently
started in the wrong one cannot pass.
---
end-to-end/README.md | 9 +++-
end-to-end/native-i18n/build.gradle | 45 +++++++++++++------
.../init/nativei18n/Application.groovy | 15 ++++++-
3 files changed, 53 insertions(+), 16 deletions(-)
diff --git a/end-to-end/README.md b/end-to-end/README.md
index eb58979ed95..44559c16e6b 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -88,8 +88,13 @@ cd end-to-end
```
The JVM half runs in `check` and needs nothing special. It cannot falsify a hint; its value is as a
-fixture guard, keeping the bundles and the assertions from drifting apart. The native half is opt-in
-because it needs a GraalVM toolchain and minutes of CPU.
+fixture guard, keeping the bundles and the assertions from drifting apart. It starts the packaged
+application twice: in production, the environment the image starts in, and in development, the
+environment `grails run-app` starts in, with reloading on, where bundles stopped resolving until
+#16179. Every run is told which environment to expect and fails in any other, since the Grails Gradle
+plugin starts every application task in development unless told otherwise.
+
+The native half is opt-in because it needs a GraalVM toolchain and minutes of CPU.
The native half needs no recorded metadata. Nothing traced by an agent is checked in or generated: the
image is built from what the framework registers while the code is generated -- finding the plugins,
diff --git a/end-to-end/native-i18n/build.gradle b/end-to-end/native-i18n/build.gradle
index de971e8aeba..d6ee23d0d4b 100644
--- a/end-to-end/native-i18n/build.gradle
+++ b/end-to-end/native-i18n/build.gradle
@@ -38,20 +38,38 @@ apply {
from rootProject.layout.projectDirectory.file('../gradle/grails-extension-gradle-config.gradle')
}
-// Runs on any JDK, and proves only that the fixture and its assertions are self-consistent - on a
-// JVM every bundle is readable whether it was registered or not. Cheap enough to keep in `check` so
-// the assertions cannot drift from the bundles while the native job is not being run.
-tasks.register('i18nCheckOnJvm', JavaExec) {
- group = 'verification'
- description = 'Resolves every message bundle from the packaged application on a JVM'
- dependsOn tasks.named('bootJar')
- classpath = files(tasks.named('bootJar').flatMap { it.archiveFile })
- mainClass = 'org.springframework.boot.loader.launch.JarLauncher'
- args = ['--i18n-check', '--server.port=0', '--spring.main.banner-mode=off']
+// What makes the application check itself, and the environment it must find it started in: Spring Boot reads
+// every --name=value argument as a property, which is how the application is told.
+def i18nCheckArgs = { String environment ->
+ ['--i18n-check', "--i18n.check.environment=${environment}".toString(), '--server.port=0',
+ '--spring.main.banner-mode=off']
}
+// Runs the packaged application on any JDK in the given environment. It proves only that the fixture and its
+// assertions are self-consistent - on a JVM every bundle is readable whether it was registered or not - and is
+// cheap enough to keep in `check`, so the assertions cannot drift from the bundles between native runs. The
+// Grails Gradle plugin starts every JavaExec in development unless told otherwise, so each sets its own.
+def registerJvmCheck = { String name, String environment ->
+ tasks.register(name, JavaExec) {
+ group = 'verification'
+ description = "Resolves every message bundle from the packaged application on a JVM, in ${environment}"
+ dependsOn tasks.named('bootJar')
+ classpath = files(tasks.named('bootJar').flatMap { it.archiveFile })
+ mainClass = 'org.springframework.boot.loader.launch.JarLauncher'
+ systemProperty 'grails.env', environment
+ args = i18nCheckArgs(environment)
+ }
+}
+
+// In production, the environment the image starts in.
+registerJvmCheck('i18nCheckOnJvm', 'production')
+
+// In development as well, the environment `grails run-app` starts in, with reloading on. Bundles that resolved
+// in production did not here until #16179, and it was this run that found it.
+registerJvmCheck('i18nCheckOnJvmInDevelopment', 'development')
+
tasks.named('check') {
- dependsOn tasks.named('i18nCheckOnJvm')
+ dependsOn tasks.named('i18nCheckOnJvm'), tasks.named('i18nCheckOnJvmInDevelopment')
}
// The native half is opt-in: it needs a GraalVM toolchain and several minutes of CPU, which is too
@@ -81,10 +99,11 @@ if (project.hasProperty('nativeTests')) {
// The path comes from the task that produces the binary, so the location and the dependency
// on its producer stay in one place rather than repeating the layout convention here.
Provider binary = tasks.named('nativeCompile').flatMap { it.outputFile }
+ // An image starts in the environment its packaged build information names, which is production.
+ List checkArgs = i18nCheckArgs('production')
inputs.file(binary)
doFirst {
- commandLine binary.get().asFile.absolutePath,
- '--i18n-check', '--server.port=0', '--spring.main.banner-mode=off'
+ commandLine([binary.get().asFile.absolutePath] + checkArgs)
}
}
diff --git a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
index e8cf7906151..cf43229fa42 100644
--- a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
+++ b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
@@ -23,6 +23,7 @@ import groovy.transform.CompileStatic
import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
+import grails.util.Environment
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.context.MessageSource
@@ -50,6 +51,12 @@ import org.springframework.context.MessageSource
* It also reads a value from the plugin's {@code plugin.yml}, which on a JVM is found beside the plugin's
* classes and in an image only through the copy the build makes of it under the plugin's name.
*
+ * Every run is told which environment it should have started in, through the property
+ * {@code i18n.check.environment}, and fails in any other. An image reads its environment from the build
+ * information packaged into it, and a run on a JVM from {@code grails.env}, which the Grails Gradle plugin
+ * sets to development for every task that runs an application. Either going wrong would check a
+ * different startup from the one intended.
+ *
* Compiled statically, as a generated application's {@code Application} class is, so that the
* image depends on resource hints for what this checks and not on reflection metadata for how it
* checks it.
@@ -66,6 +73,12 @@ class Application extends GrailsAutoConfiguration {
ConfigurableApplicationContext context = GrailsApp.run(Application, args)
int exitCode = 0
try {
+ String expectedEnvironment = context.environment.getProperty('i18n.check.environment')
+ if (Environment.current.name != expectedEnvironment) {
+ throw new IllegalStateException("The application started in ${Environment.current.name}, " +
+ "not in ${expectedEnvironment}, the environment i18n.check.environment names")
+ }
+
MessageSource messages = context.getBean(MessageSource)
// The application's own bundle, base name 'messages' — the one case Boot's hints cover.
@@ -108,7 +121,7 @@ class Application extends GrailsAutoConfiguration {
"native.plugin.configuration was '${configured}'")
}
- println 'i18n-check: every message bundle resolved, and the plugin configuration was read'
+ println "i18n-check: in ${expectedEnvironment}, every message bundle resolved, and the plugin configuration was read"
}
catch (Throwable failure) {
failure.printStackTrace()
From d8edebdd2e66b2afa0d1aa3d2f90ec235c7e7866 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Wed, 21 Oct 2026 08:58:32 -0600
Subject: [PATCH 31/39] Build and run the native-i18n image in CI
The native half had no CI job: a native compile takes minutes of CPU and
needs a GraalVM no other job uses. It now runs at the end of the End to End
job, which has already published the framework the image is built from, so
nothing is published twice. GraalVM Community 25 is set up only for that
step and leaves JAVA_HOME to the JDK the rest of the job uses. The step runs
whether or not the end-to-end tests before it passed.
---
.github/workflows/end-to-end.yml | 30 ++++++++++++++++++++++++++++++
end-to-end/README.md | 3 ++-
2 files changed, 32 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/end-to-end.yml b/.github/workflows/end-to-end.yml
index 3986680e065..24d1728201c 100644
--- a/.github/workflows/end-to-end.yml
+++ b/.github/workflows/end-to-end.yml
@@ -32,6 +32,9 @@
# root .sdkmanrc - it has to run on whatever the core build it consumes runs on - and only the
# fixture carries its own pin. The steps below read both out of those files rather than relying
# on Gradle toolchain auto-detection.
+#
+# A third, GraalVM 25, builds the native-i18n image at the end of the job, from the same published
+# artifacts.
name: "End to End"
on:
push:
@@ -90,6 +93,7 @@ jobs:
working-directory: 'grails-gradle'
run: ./gradlew publishAllPublicationsToTestCaseMavenRepoRepository -PskipTests --stacktrace
- name: "📦 Setup: publish Grails to the local repository the tests resolve from"
+ id: publish-grails
run: ./gradlew publishAllPublicationsToTestCaseMavenRepoRepository -PskipTests --stacktrace
- name: "📦 Setup: build the precompiled Grails 7 / Groovy 4 fixture"
working-directory: 'end-to-end/legacy-g7-command-plugin'
@@ -134,6 +138,32 @@ jobs:
env:
DO_NOT_CACHE_TESTS: '1'
run: ./gradlew check --continue --stacktrace
+ - name: "☕️ Setup GraalVM for the native image"
+ # In this job rather than its own, so the image is built from the framework published above
+ # instead of publishing it a second time. It runs whether or not the tests above passed, and
+ # leaves JAVA_HOME alone: only the step below uses GraalVM.
+ if: ${{ !cancelled() && steps.publish-grails.outcome == 'success' }}
+ uses: graalvm/setup-graalvm@27b360dbb857524eaf0b4c4cef364d38e5b4f173 # v1.6.7
+ with:
+ distribution: graalvm-community
+ java-version: '25'
+ set-java-home: 'false'
+ check-for-updates: 'false'
+ - name: "🧪 Build and run the native-i18n image"
+ # The native half of native-i18n: compile the application to a binary with no recorded
+ # metadata and resolve every message bundle from it. GraalVM 25 or later, because the 21 line
+ # cannot compile Groovy 4 or later (oracle/graal#10200); see end-to-end/README.md.
+ if: ${{ !cancelled() && steps.publish-grails.outcome == 'success' }}
+ working-directory: 'end-to-end'
+ env:
+ JAVA_HOME: ${{ env.GRAALVM_HOME }}
+ run: |
+ set -euo pipefail
+ if [ -z "${JAVA_HOME:-}" ]; then
+ echo "setup-graalvm did not set GRAALVM_HOME; refusing to build the image on another JDK" >&2
+ exit 1
+ fi
+ ./gradlew :native-i18n:i18nCheckOnNative -PnativeTests --stacktrace
- name: "📤 Upload test reports"
if: failure()
uses: actions/upload-artifact@v7.0.1
diff --git a/end-to-end/README.md b/end-to-end/README.md
index 44559c16e6b..da3a6ea2712 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -94,7 +94,8 @@ environment `grails run-app` starts in, with reloading on, where bundles stopped
#16179. Every run is told which environment to expect and fails in any other, since the Grails Gradle
plugin starts every application task in development unless told otherwise.
-The native half is opt-in because it needs a GraalVM toolchain and minutes of CPU.
+The native half is opt-in because it needs a GraalVM toolchain and minutes of CPU. CI runs it at the
+end of the End to End job, against the framework that job publishes.
The native half needs no recorded metadata. Nothing traced by an agent is checked in or generated: the
image is built from what the framework registers while the code is generated -- finding the plugins,
From 6f3d5148ee8ac7a77c9bbd9ab00d9c030e9fb134 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Wed, 21 Oct 2026 15:54:56 -0400
Subject: [PATCH 32/39] Build the native-i18n image in CI with GraalVM 25.2
The first CI run of the native step failed in "Initializing" with
"Could not find target method: ...IndyInterface.invalidateSwitchPoints()",
the bundled Groovy substitution of oracle/graal#10200. setup-graalvm
resolved java-version '25' to GraalVM CE 25.0.2, the last release tagged
by JDK version, and that release still has the substitution. Releases
since are tagged by GraalVM version (graal-25.2.4 and later), which a
java-version alone never selects.
Asking for version '25.2' selects graal-25.2.4, the release the image
was verified with locally. The README said the fix was in "the 25 line";
it now says which releases fail and how to ask for one that works.
---
.github/workflows/end-to-end.yml | 11 ++++++++---
end-to-end/README.md | 10 ++++++----
2 files changed, 14 insertions(+), 7 deletions(-)
diff --git a/.github/workflows/end-to-end.yml b/.github/workflows/end-to-end.yml
index da0c3eb2e69..8fc4a5a7cfb 100644
--- a/.github/workflows/end-to-end.yml
+++ b/.github/workflows/end-to-end.yml
@@ -33,7 +33,7 @@
# fixture carries its own pin. The steps below read both out of those files rather than relying
# on Gradle toolchain auto-detection.
#
-# A third, GraalVM 25, builds the native-i18n image at the end of the job, from the same published
+# A third, GraalVM 25.2, builds the native-i18n image at the end of the job, from the same published
# artifacts.
name: "End to End"
on:
@@ -165,13 +165,18 @@ jobs:
uses: graalvm/setup-graalvm@27b360dbb857524eaf0b4c4cef364d38e5b4f173 # v1.6.7
with:
distribution: graalvm-community
+ # The GraalVM release, not just the JDK: a java-version alone resolves to the last release tagged
+ # by JDK version, CE 25.0.2, which still cannot compile Groovy 4 or later. Releases since are
+ # tagged by GraalVM version, which is what this selects.
+ version: '25.2'
java-version: '25'
set-java-home: 'false'
check-for-updates: 'false'
- name: "🧪 Build and run the native-i18n image"
# The native half of native-i18n: compile the application to a binary with no recorded
- # metadata and resolve every message bundle from it. GraalVM 25 or later, because the 21 line
- # cannot compile Groovy 4 or later (oracle/graal#10200); see end-to-end/README.md.
+ # metadata and resolve every message bundle from it. GraalVM 25.2 or later, because GraalVM 21 and
+ # the first GraalVM 25 releases cannot compile Groovy 4 or later (oracle/graal#10200); see
+ # end-to-end/README.md.
if: ${{ !cancelled() && steps.publish-grails.outcome == 'success' }}
working-directory: 'end-to-end'
env:
diff --git a/end-to-end/README.md b/end-to-end/README.md
index da3a6ea2712..b3275dde304 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -124,10 +124,12 @@ image is not a Grails 8 capability and this module is not on that branch.
**A GraalVM JDK, and not necessarily the one that published the framework.** `GRAALVM_HOME` and
`JAVA_HOME` must point at a GraalVM before the image is built; `toolchainDetection = false` makes the
plugin honour it rather than resolving a toolchain, so the publish JDK and the image JDK do not have
-to agree. Use GraalVM 25 or later: on the 21 line `nativeCompile` fails during "Initializing" with
-`Could not find target method: ...IndyInterface.invalidateSwitchPoints()`, because GraalVM's bundled
-Groovy substitution targets a method Groovy 4+ removed
-([oracle/graal#10200](https://github.com/oracle/graal/issues/10200), fixed in the 25 line). What must
+to agree. Use GraalVM 25.2 or later. GraalVM 21, and GraalVM 25 up to CE 25.0.2, fail `nativeCompile`
+during "Initializing" with `Could not find target method: ...IndyInterface.invalidateSwitchPoints()`,
+because their bundled Groovy substitution targets a method Groovy 4+ removed
+([oracle/graal#10200](https://github.com/oracle/graal/issues/10200)); 25.2.4 builds the image. GraalVM
+releases after CE 25.0.2 are numbered by GraalVM version rather than JDK version, so ask for the
+GraalVM release itself: `25.2.4-graalce` with SDKMAN, or `version: '25.2'` with `setup-graalvm`. What must
not happen is publishing on a JDK *newer* than the one the image is built with: `GroovyCompile` has
no `release` option, so the Groovy sources in `grails-gradle` are compiled for the running JDK, and a
newer class file version makes the image fail at *configuration* time, naming a framework class as
From 5d1cde22d889f8594b33450609bcd8ce80095eab Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 22 Oct 2026 12:48:31 -0600
Subject: [PATCH 33/39] Say the framework's list covers starting the
application, and a request's path is still recorded
---
grails-doc/src/en/guide/deployment/deploymentAot.adoc | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index 1dcaec8c80a..2197a07ab78 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
@@ -118,7 +118,7 @@ Starting an application needs reflection the framework does on its own behalf, a
* what Groovy does reflectively even for statically compiled classes, in the framework and in the application's own packages: creating a Groovy enum's constants, initializing a trait from a class that implements it, and turning a closure into the interface a method takes;
* the build information that says which environment the application was packaged for, and the default validation messages.
-What remains the application's is the reflection its own dynamically compiled code does. A call written without static compilation is resolved where it is made, against whatever it is made on, and only a run shows what that is. Compile such code statically, as a generated application's `Application` class is, or record what it does as described below.
+The list covers starting the application. What a request reaches is still recorded, as described below, and that covers two things: the framework's own reflection along the request's path, and the reflection the application's own dynamically compiled code does. A call written without static compilation is resolved where it is made, against whatever it is made on, and only a run shows what that is. Compiling the application's code statically, as a generated application's `Application` class is, takes its own calls out of what has to be recorded, but not the framework's reflection on a request's path.
==== Recording reflection for a native image
From 228be69186390bd1318843acead44cc695deacf8 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 22 Oct 2026 12:48:45 -0600
Subject: [PATCH 34/39] Find a closure dynamically compiled code coerces with
as
Dynamically compiled code compiles `{ ... } as SomeInterface` to an indy call to asType taking the
Closure and the interface's class literal, loaded right before it, rather than to a cast. Only the
cast was found, so a dynamic plugin descriptor's beanRegistrar() worked in an image only because
another plugin coerced a closure to the same interface under static compilation.
A closure dynamically compiled code passes to a method is an ordinary call with a Closure argument
and cannot be found from the bytecode; the javadoc and the guide now say only the forms that name
the interface are found.
---
.../grails/core/aot/BytecodeRuntimeHints.java | 179 ++++++++++++++----
.../grails/core/aot/BytecodeFixtures.groovy | 14 ++
.../core/aot/BytecodeRuntimeHintsSpec.groovy | 16 ++
.../en/guide/deployment/deploymentAot.adoc | 4 +-
4 files changed, 179 insertions(+), 34 deletions(-)
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
index ff41e58d49a..22bd181e2e3 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
@@ -44,6 +44,7 @@
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.FieldVisitor;
import org.springframework.asm.Handle;
+import org.springframework.asm.Label;
import org.springframework.asm.MethodVisitor;
import org.springframework.asm.SpringAsmInfo;
import org.springframework.asm.Type;
@@ -65,10 +66,14 @@
* one, so its constructors have to be visible. {@code grails.util.Environment} is one, and it is the first
* thing an application touches: without this an image fails before Spring has started, with "Could not
* find matching constructor".
- * A closure passed where a method takes an interface -- {@code removeIf}, {@code forEach},
- * {@code computeIfAbsent}, a plugin's {@code BeanRegistrar} -- is turned into that interface by a JDK proxy
- * created as the call is made. An image creates a proxy only for an interface it was told about, and
- * refuses the rest with {@code MissingReflectionRegistrationError}.
+ * A closure turned into an interface -- passed where a method takes one, such as {@code removeIf},
+ * {@code forEach} or {@code computeIfAbsent}, or coerced with {@code as}, as a plugin's
+ * {@code BeanRegistrar} often is -- becomes it through a JDK proxy created as the call is made. An image
+ * creates a proxy only for an interface it was told about, and refuses the rest with
+ * {@code MissingReflectionRegistrationError}. Only a coercion that names the interface is found: any in
+ * statically compiled code, and an {@code as} with a class literal in dynamically compiled code. A closure
+ * that dynamically compiled code passes to a method is an ordinary call with a {@code Closure} argument,
+ * which does not say what it will become, so it is not found.
* A class implementing a trait initializes it from its constructor by calling the trait's helper class
* through {@code ScriptBytecodeAdapter.invokeMethodN}, a dynamic call. The framework's traits are on the
* application class, the controllers, the tag libraries and the domain classes, so without this none of
@@ -89,7 +94,8 @@
*
* All of it is found by reading the bytecode while the hints are written, which happens during the build
* on an ordinary JVM with the full classpath: an enum is a class extending {@code Enum} that implements
- * {@code GroovyObject}, a coercion is an invokedynamic {@code cast} from {@code Closure} to an interface, a
+ * {@code GroovyObject}, a coercion is an invokedynamic {@code cast} from {@code Closure} to an interface or
+ * a dynamic call to {@code asType} taking a {@code Closure} right after a class literal naming one, a
* trait's helpers are the classes Groovy names {@code $Trait$Helper}, {@code $Trait$FieldHelper} and
* {@code $Trait$StaticFieldHelper}, an injected member carries its annotation, and a Groovy class is one
* that implements {@code GroovyObject}, directly or through a superclass. The framework compiles
@@ -117,8 +123,14 @@ public class BytecodeRuntimeHints implements RuntimeHintsRegistrar {
private static final String CAST = "cast";
+ private static final String INVOKE = "invoke";
+
+ private static final String AS_TYPE = "asType";
+
private static final String CLOSURE = "Lgroovy/lang/Closure;";
+ private static final String CLASS = "Ljava/lang/Class;";
+
/** How Groovy names the classes that carry a trait's methods and fields. */
private static final String[] TRAIT_HELPER_SUFFIXES = {
"$Trait$Helper", "$Trait$FieldHelper", "$Trait$StaticFieldHelper"
@@ -282,8 +294,8 @@ private void register(RuntimeHints hints, ClassLoader loader) {
}
/**
- * Collects whether a class is a Groovy enum or a trait's helper, the interfaces its closures are cast to,
- * and the members it has annotated for Spring.
+ * Collects whether a class is a Groovy enum or a trait's helper and the fields it has annotated for Spring,
+ * and reads each of its methods with a {@link FindingMethodVisitor}.
*/
private static final class FindingClassVisitor extends ClassVisitor {
@@ -330,36 +342,139 @@ public AnnotationVisitor visitAnnotation(String annotation, boolean visible) {
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, String signature,
String[] exceptions) {
- return new MethodVisitor(SpringAsmInfo.ASM_VERSION) {
- @Override
- public AnnotationVisitor visitAnnotation(String annotation, boolean visible) {
- if (SPRING_ANNOTATIONS.contains(annotation)) {
- List parameterTypes = new ArrayList<>();
- for (Type parameter : Type.getArgumentTypes(descriptor)) {
- parameterTypes.add(TypeReference.of(parameter.getClassName()));
- }
- findings.invokedMethods.computeIfAbsent(className, type -> new LinkedHashSet<>())
- .add(new MethodSignature(name, parameterTypes));
- }
- return null;
+ return new FindingMethodVisitor(findings, className, name, descriptor);
+ }
+
+ }
+
+ /**
+ * Collects the members a method has annotated for Spring and the interfaces its closures are turned into.
+ */
+ private static final class FindingMethodVisitor extends MethodVisitor {
+
+ private final Findings findings;
+
+ private final String className;
+
+ private final String name;
+
+ private final String descriptor;
+
+ /** The class the previous instruction named with a literal, which {@code as} takes its target from. */
+ @Nullable
+ private Type classLiteral;
+
+ private FindingMethodVisitor(Findings findings, String className, String name, String descriptor) {
+ super(SpringAsmInfo.ASM_VERSION);
+ this.findings = findings;
+ this.className = className;
+ this.name = name;
+ this.descriptor = descriptor;
+ }
+
+ @Override
+ public AnnotationVisitor visitAnnotation(String annotation, boolean visible) {
+ if (SPRING_ANNOTATIONS.contains(annotation)) {
+ List parameterTypes = new ArrayList<>();
+ for (Type parameter : Type.getArgumentTypes(descriptor)) {
+ parameterTypes.add(TypeReference.of(parameter.getClassName()));
}
+ findings.invokedMethods.computeIfAbsent(className, type -> new LinkedHashSet<>())
+ .add(new MethodSignature(name, parameterTypes));
+ }
+ return null;
+ }
- @Override
- public void visitInvokeDynamicInsn(String methodName, String methodDescriptor, Handle bootstrap,
- Object... bootstrapArguments) {
- if (!CAST.equals(methodName) || !INDY_INTERFACE.equals(bootstrap.getOwner())) {
- return;
- }
- Type[] arguments = Type.getArgumentTypes(methodDescriptor);
- Type target = Type.getReturnType(methodDescriptor);
- if (arguments.length == 1 && CLOSURE.equals(arguments[0].getDescriptor()) &&
- target.getSort() == Type.OBJECT) {
- findings.coercedTo.add(target.getClassName());
- }
+ /**
+ * Finds the two ways a closure is turned into an interface that name the interface: a cast, which
+ * statically compiled code and a typed assignment make, and {@code as} with a class literal, which
+ * dynamically compiled code makes as a call to {@code asType} right after the literal.
+ */
+ @Override
+ public void visitInvokeDynamicInsn(String methodName, String methodDescriptor, Handle bootstrap,
+ Object... bootstrapArguments) {
+ Type named = classLiteral;
+ classLiteral = null;
+ if (!INDY_INTERFACE.equals(bootstrap.getOwner())) {
+ return;
+ }
+ Type[] arguments = Type.getArgumentTypes(methodDescriptor);
+ if (arguments.length == 0 || !CLOSURE.equals(arguments[0].getDescriptor())) {
+ return;
+ }
+ if (CAST.equals(methodName) && arguments.length == 1) {
+ Type target = Type.getReturnType(methodDescriptor);
+ if (target.getSort() == Type.OBJECT) {
+ findings.coercedTo.add(target.getClassName());
}
- };
+ }
+ else if (INVOKE.equals(methodName) && arguments.length == 2 &&
+ CLASS.equals(arguments[1].getDescriptor()) && bootstrapArguments.length > 0 &&
+ AS_TYPE.equals(bootstrapArguments[0]) && named != null) {
+ findings.coercedTo.add(named.getClassName());
+ }
+ }
+
+ @Override
+ public void visitLdcInsn(Object value) {
+ classLiteral = (value instanceof Type type && type.getSort() == Type.OBJECT) ? type : null;
+ }
+
+ @Override
+ public void visitInsn(int opcode) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitIntInsn(int opcode, int operand) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitVarInsn(int opcode, int varIndex) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitTypeInsn(int opcode, String type) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitFieldInsn(int opcode, String owner, String fieldName, String fieldDescriptor) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitMethodInsn(int opcode, String owner, String methodName, String methodDescriptor,
+ boolean isInterface) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitJumpInsn(int opcode, Label label) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitIincInsn(int varIndex, int increment) {
+ classLiteral = null;
}
+ @Override
+ public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
+ classLiteral = null;
+ }
+
+ @Override
+ public void visitMultiANewArrayInsn(String arrayDescriptor, int dimensions) {
+ classLiteral = null;
+ }
}
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
index 2df7d989e64..5311e4354e4 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
@@ -18,6 +18,7 @@
*/
package org.apache.grails.core.aot
+import java.util.function.IntUnaryOperator
import java.util.stream.IntStream
import groovy.transform.CompileStatic
@@ -50,6 +51,19 @@ class ClosureCoercionFixture {
}
}
+/**
+ * A closure turned into an interface with {@code as} in a dynamically compiled class, as a plugin's
+ * {@code beanRegistrar()} often is. Groovy compiles it to a call to {@code asType}, not to a cast.
+ * {@code IntUnaryOperator} because nothing in the framework coerces a closure to it, so finding it proves
+ * this class was read.
+ */
+class DynamicCoercionFixture {
+
+ static IntUnaryOperator doubling() {
+ { int operand -> operand * 2 } as IntUnaryOperator
+ }
+}
+
/**
* A trait with a field, so Groovy writes both a helper and a field helper for it, and a class implementing
* it initializes it from its constructor through the helper.
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
index 5943624b271..5f5af0a03cb 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
@@ -18,7 +18,9 @@
*/
package org.apache.grails.core.aot
+import java.lang.reflect.Proxy
import java.util.function.IntBinaryOperator
+import java.util.function.IntUnaryOperator
import org.springframework.aot.hint.MemberCategory
import org.springframework.aot.hint.RuntimeHints
@@ -66,6 +68,11 @@ class BytecodeRuntimeHintsSpec extends Specification {
RuntimeHintsPredicates.proxies().forInterfaces(IntBinaryOperator).test(hints)
}
+ void 'an interface a dynamically compiled class coerces a closure to with as can be proxied'() {
+ expect: 'dynamic code makes the coercion a call to asType right after naming the interface, not a cast'
+ RuntimeHintsPredicates.proxies().forInterfaces(IntUnaryOperator).test(hints)
+ }
+
void 'a trait can be initialized by the classes implementing it'() {
given: 'the helpers Groovy writes for a trait with a field, by the names an image is told'
def helper = TypeReference.of(GreetingTraitFixture.name + '$Trait$Helper')
@@ -117,6 +124,15 @@ class BytecodeRuntimeHintsSpec extends Specification {
ClosureCoercionFixture.sum(4) == 6
}
+ void 'the dynamic coercion still makes a JDK proxy'() {
+ when:
+ def doubling = DynamicCoercionFixture.doubling()
+
+ then: 'the fixture is the code the hint is for, so it has to do what it says'
+ Proxy.isProxyClass(doubling.getClass())
+ doubling.applyAsInt(21) == 42
+ }
+
void 'the trait still initializes'() {
expect: 'the fixture is the code the hint is for, so it has to do what it says'
new GreeterFixture().greeting == 'hello'
diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index 2197a07ab78..bf2ce62431c 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
@@ -115,10 +115,10 @@ Starting an application needs reflection the framework does on its own behalf, a
* the classes listed in `META-INF/grails.factories`, such as the artefact handlers;
* the beans the plugins declare, through a `BeanRegistrar` or the bean DSL, which are declared again as the application starts and created and wired from there;
* the artefacts the application holds -- including ones it did not write, such as the default URL mappings -- and the artefacts the plugins provide, such as the codecs;
-* what Groovy does reflectively even for statically compiled classes, in the framework and in the application's own packages: creating a Groovy enum's constants, initializing a trait from a class that implements it, and turning a closure into the interface a method takes;
+* what Groovy does reflectively even for statically compiled classes, in the framework and in the application's own packages: creating a Groovy enum's constants, initializing a trait from a class that implements it, and turning a closure into an interface, wherever statically compiled code does it and wherever dynamically compiled code names the interface with `as`;
* the build information that says which environment the application was packaged for, and the default validation messages.
-The list covers starting the application. What a request reaches is still recorded, as described below, and that covers two things: the framework's own reflection along the request's path, and the reflection the application's own dynamically compiled code does. A call written without static compilation is resolved where it is made, against whatever it is made on, and only a run shows what that is. Compiling the application's code statically, as a generated application's `Application` class is, takes its own calls out of what has to be recorded, but not the framework's reflection on a request's path.
+The list covers starting the application. What a request reaches is still recorded, as described below, and that covers two things: the framework's own reflection along the request's path, and the reflection the application's own dynamically compiled code does. A call written without static compilation is resolved where it is made, against whatever it is made on, and only a run shows what that is. That includes a closure such code passes to a method taking an interface: the closure becomes that interface through a proxy, and nothing in the compiled call names which. Compiling the application's code statically, as a generated application's `Application` class is, takes its own calls out of what has to be recorded, but not the framework's reflection on a request's path.
==== Recording reflection for a native image
From 3dee35205b08f5f5d4a4bd789b571632f3d41e93 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 22 Oct 2026 12:51:31 -0600
Subject: [PATCH 35/39] Skip a scanned class whose bytecode names a class that
is absent
Only a class registered for the setProperty lookup was asked whether every type its bytecode names
loads. A Groovy enum, a trait helper and a class with members Spring injects were asked only whether
they load, which a class does without what its method bodies name, so one compiled against an
optional integration the application lacks was registered and would fail the image build.
Every class the scan read is now asked both, and the spec covers each of those paths and a class
whose file is found but which does not load.
---
.../grails/core/aot/BytecodeRuntimeHints.java | 26 ++++++++---
.../grails/core/aot/BytecodeFixtures.groovy | 40 +++++++++++++++++
.../core/aot/BytecodeRuntimeHintsSpec.groovy | 44 +++++++++++++++++++
3 files changed, 103 insertions(+), 7 deletions(-)
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
index 22bd181e2e3..7a5e0faf793 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
@@ -99,8 +99,8 @@
* trait's helpers are the classes Groovy names {@code $Trait$Helper}, {@code $Trait$FieldHelper} and
* {@code $Trait$StaticFieldHelper}, an injected member carries its annotation, and a Groovy class is one
* that implements {@code GroovyObject}, directly or through a superclass. The framework compiles
- * against optional integrations, so a class that cannot be loaded here is skipped rather than registered,
- * as {@link GrailsClosureRuntimeHints} does for closures.
+ * against optional integrations, so a class that cannot be loaded here, or whose bytecode names one that
+ * cannot, is skipped rather than registered, as {@link GrailsClosureRuntimeHints} does for closures.
*
* @since 9.0
*/
@@ -218,6 +218,18 @@ private static boolean isGroovyClass(String className, Resource resource, ClassL
if (type == null || type.isInterface() || !GroovyObject.class.isAssignableFrom(type)) {
return false;
}
+ return referencesLoad(resource, loader);
+ }
+
+ /**
+ * Whether a class the scan read can be registered: it loads here, and its bytecode names nothing absent
+ * here. Loading resolves signatures and not bodies, so a class loads without what its methods name.
+ */
+ private static boolean isRegistrable(String className, @Nullable Resource resource, ClassLoader loader) {
+ return resource != null && load(className, loader) != null && referencesLoad(resource, loader);
+ }
+
+ private static boolean referencesLoad(Resource resource, ClassLoader loader) {
try {
return RegistrableTypes.referencesLoad(resource.getInputStream(), loader);
}
@@ -248,12 +260,12 @@ private static final class Findings {
private final Map> invokedMethods = new LinkedHashMap<>();
- /** Every class read, with where it was read from, to be asked whether it is a Groovy class. */
+ /** Every class read, with where it was read from, to be asked whether it can be registered. */
private final Map classes = new LinkedHashMap<>();
private void register(RuntimeHints hints, ClassLoader loader) {
for (String type : enums) {
- if (load(type, loader) != null) {
+ if (isRegistrable(type, classes.get(type), loader)) {
hints.reflection().registerType(TypeReference.of(type), MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
}
@@ -264,17 +276,17 @@ private void register(RuntimeHints hints, ClassLoader loader) {
}
}
for (String type : traitHelpers) {
- if (load(type, loader) != null) {
+ if (isRegistrable(type, classes.get(type), loader)) {
hints.reflection().registerType(TypeReference.of(type), MemberCategory.INVOKE_DECLARED_METHODS);
}
}
injectedFields.forEach((type, fields) -> {
- if (load(type, loader) != null) {
+ if (isRegistrable(type, classes.get(type), loader)) {
hints.reflection().registerType(TypeReference.of(type), builder -> fields.forEach(builder::withField));
}
});
invokedMethods.forEach((type, methods) -> {
- if (load(type, loader) != null) {
+ if (isRegistrable(type, classes.get(type), loader)) {
hints.reflection().registerType(TypeReference.of(type), builder -> methods.forEach(method ->
builder.withMethod(method.name(), method.parameterTypes(), ExecutableMode.INVOKE)));
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
index 5311e4354e4..b84520ba192 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
@@ -98,3 +98,43 @@ class AnnotatedMembersFixture {
void close() {
}
}
+
+/** A class an application without an optional dependency does not have. */
+class OptionalDependencyFixture {
+}
+
+/**
+ * A Groovy enum naming {@link OptionalDependencyFixture} only in a method body, so it loads without it, as a
+ * class compiled against an optional integration does.
+ */
+enum OptionalDependencyEnumFixture {
+ ONLY
+
+ Object dependency() {
+ new OptionalDependencyFixture()
+ }
+}
+
+/** A trait naming {@link OptionalDependencyFixture} in a method, which its helper then carries. */
+trait OptionalDependencyTraitFixture {
+
+ Object dependency() {
+ new OptionalDependencyFixture()
+ }
+}
+
+/** A bean with a member Spring injects, naming {@link OptionalDependencyFixture} only in a method body. */
+class OptionalDependencyBeanFixture {
+
+ @Autowired
+ private Object collaborator
+
+ Object dependency() {
+ new OptionalDependencyFixture()
+ }
+}
+
+/** A Groovy enum whose class file a scan finds, but which the application cannot load. */
+enum UnloadableFixture {
+ ONLY
+}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
index 5f5af0a03cb..768e3988362 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
@@ -41,8 +41,27 @@ class BytecodeRuntimeHintsSpec extends Specification {
@Shared
RuntimeHints hints = new RuntimeHints()
+ @Shared
+ RuntimeHints hintsWithoutOptionalClasses = new RuntimeHints()
+
void setupSpec() {
new BytecodeRuntimeHints().registerHints(hints, getClass().classLoader)
+ new BytecodeRuntimeHints().registerHints(hintsWithoutOptionalClasses,
+ without(OptionalDependencyFixture, UnloadableFixture))
+ }
+
+ /** A loader that cannot load the given classes, as an application without an optional dependency cannot. */
+ private ClassLoader without(Class>... absent) {
+ Set names = absent*.name as Set
+ new ClassLoader(getClass().classLoader) {
+ @Override
+ protected Class> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+ if (name in names) {
+ throw new ClassNotFoundException(name)
+ }
+ super.loadClass(name, resolve)
+ }
+ }
}
void 'a Groovy enum can have its constants created'() {
@@ -119,6 +138,31 @@ class BytecodeRuntimeHintsSpec extends Specification {
!RuntimeHintsPredicates.reflection().onType(CaffeineRuntimeHints).test(hints)
}
+ void 'a #kind whose bytecode names a class the application does not have is not registered'() {
+ expect: 'it loads, since only a method body names the absent class, but registering it in any way -- ' +
+ 'as a type, or for its constructors, methods or fields -- would fail the image build, which ' +
+ 'parses what it is asked to keep'
+ hintsWithoutOptionalClasses.reflection().typeHints().noneMatch { it.type.name == className }
+
+ and: 'it is registered where the class is there'
+ hints.reflection().typeHints().anyMatch { it.type.name == className }
+
+ where:
+ kind | className
+ 'Groovy enum' | OptionalDependencyEnumFixture.name
+ 'trait helper' | OptionalDependencyTraitFixture.name + '$Trait$Helper'
+ 'class with members Spring injects' | OptionalDependencyBeanFixture.name
+ }
+
+ void 'a class the scan finds but the application cannot load is not registered'() {
+ expect: 'its class file is read like any other'
+ hintsWithoutOptionalClasses.reflection().typeHints().noneMatch { it.type.name == UnloadableFixture.name }
+
+ and: 'it is registered, as a type and for its constructors, where it loads'
+ RuntimeHintsPredicates.reflection().onType(UnloadableFixture)
+ .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).test(hints)
+ }
+
void 'the coercion still works'() {
expect: 'the fixture is the code the hint is for, so it has to do what it says'
ClosureCoercionFixture.sum(4) == 6
From 452e34e009e630dcf2a9c47e76dccd2d527996c4 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Sat, 24 Oct 2026 08:14:49 -0700
Subject: [PATCH 36/39] Find an as coercion whatever the value is declared as
`as` with a class literal compiles to a call to asType, in statically and dynamically compiled code
alike, and the call declares the value as a Closure only when the compiler knows it is one. A def
variable or a method's result is declared as an Object, and a map literal as a Map, which Groovy
turns into an interface through a JDK proxy just as it does a closure. Those were not found, so
ConfigProperties.propertyNames(), which coerces a map literal to Enumeration, had no proxy hint.
Any asType call right after a class literal naming an interface is now found. An `as` that converts
without a proxy, such as `as List`, then registers a proxy the image never makes: on native-i18n's
classpath the rule adds seven interfaces, and only Enumeration is proxied.
---
.../grails/core/aot/BytecodeRuntimeHints.java | 33 ++++----
.../grails/core/aot/BytecodeFixtures.groovy | 84 +++++++++++++++++--
.../core/aot/BytecodeRuntimeHintsSpec.groovy | 44 +++++++---
.../en/guide/deployment/deploymentAot.adoc | 2 +-
4 files changed, 127 insertions(+), 36 deletions(-)
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
index 7a5e0faf793..2d943e733db 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
@@ -68,12 +68,14 @@
* find matching constructor".
* A closure turned into an interface -- passed where a method takes one, such as {@code removeIf},
* {@code forEach} or {@code computeIfAbsent}, or coerced with {@code as}, as a plugin's
- * {@code BeanRegistrar} often is -- becomes it through a JDK proxy created as the call is made. An image
- * creates a proxy only for an interface it was told about, and refuses the rest with
- * {@code MissingReflectionRegistrationError}. Only a coercion that names the interface is found: any in
- * statically compiled code, and an {@code as} with a class literal in dynamically compiled code. A closure
- * that dynamically compiled code passes to a method is an ordinary call with a {@code Closure} argument,
- * which does not say what it will become, so it is not found.
+ * {@code BeanRegistrar} often is -- becomes it through a JDK proxy created as the call is made, and so does
+ * a map coerced with {@code as}. An image creates a proxy only for an interface it was told about, and
+ * refuses the rest with {@code MissingReflectionRegistrationError}. Only a coercion that names the interface
+ * is found: a closure statically compiled code passes or assigns to an interface, and any {@code as} with a
+ * class literal, whatever the code knows about the value. That includes an {@code as} that converts without
+ * a proxy, such as {@code as List}, whose interface is then registered for a proxy the image never makes. A
+ * closure that dynamically compiled code passes to a method is an ordinary call with a {@code Closure}
+ * argument, which does not say what it will become, so it is not found.
* A class implementing a trait initializes it from its constructor by calling the trait's helper class
* through {@code ScriptBytecodeAdapter.invokeMethodN}, a dynamic call. The framework's traits are on the
* application class, the controllers, the tag libraries and the domain classes, so without this none of
@@ -95,7 +97,7 @@
* All of it is found by reading the bytecode while the hints are written, which happens during the build
* on an ordinary JVM with the full classpath: an enum is a class extending {@code Enum} that implements
* {@code GroovyObject}, a coercion is an invokedynamic {@code cast} from {@code Closure} to an interface or
- * a dynamic call to {@code asType} taking a {@code Closure} right after a class literal naming one, a
+ * a call to {@code asType} right after a class literal naming one, a
* trait's helpers are the classes Groovy names {@code $Trait$Helper}, {@code $Trait$FieldHelper} and
* {@code $Trait$StaticFieldHelper}, an injected member carries its annotation, and a Groovy class is one
* that implements {@code GroovyObject}, directly or through a superclass. The framework compiles
@@ -398,9 +400,12 @@ public AnnotationVisitor visitAnnotation(String annotation, boolean visible) {
}
/**
- * Finds the two ways a closure is turned into an interface that name the interface: a cast, which
- * statically compiled code and a typed assignment make, and {@code as} with a class literal, which
- * dynamically compiled code makes as a call to {@code asType} right after the literal.
+ * Finds the two ways of turning a value into an interface that name the interface: a cast from
+ * {@code Closure}, which statically compiled code makes for a closure it passes or assigns to an
+ * interface, and {@code as} with a class literal, which any code makes as a call to {@code asType}
+ * right after the literal. The value's declared type is not asked: the call declares a {@code Closure}
+ * only when the compiler knows the value is one, an {@code Object} for a {@code def} variable or a
+ * method's result, and a {@code Map} for a map literal, which is proxied as a closure is.
*/
@Override
public void visitInvokeDynamicInsn(String methodName, String methodDescriptor, Handle bootstrap,
@@ -411,12 +416,10 @@ public void visitInvokeDynamicInsn(String methodName, String methodDescriptor, H
return;
}
Type[] arguments = Type.getArgumentTypes(methodDescriptor);
- if (arguments.length == 0 || !CLOSURE.equals(arguments[0].getDescriptor())) {
- return;
- }
- if (CAST.equals(methodName) && arguments.length == 1) {
+ if (CAST.equals(methodName)) {
Type target = Type.getReturnType(methodDescriptor);
- if (target.getSort() == Type.OBJECT) {
+ if (arguments.length == 1 && CLOSURE.equals(arguments[0].getDescriptor()) &&
+ target.getSort() == Type.OBJECT) {
findings.coercedTo.add(target.getClassName());
}
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
index b84520ba192..0a861559c9d 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
@@ -18,7 +18,6 @@
*/
package org.apache.grails.core.aot
-import java.util.function.IntUnaryOperator
import java.util.stream.IntStream
import groovy.transform.CompileStatic
@@ -52,16 +51,87 @@ class ClosureCoercionFixture {
}
/**
- * A closure turned into an interface with {@code as} in a dynamically compiled class, as a plugin's
- * {@code beanRegistrar()} often is. Groovy compiles it to a call to {@code asType}, not to a cast.
- * {@code IntUnaryOperator} because nothing in the framework coerces a closure to it, so finding it proves
- * this class was read.
+ * Values turned into interfaces with {@code as} in a dynamically compiled class, as a plugin's
+ * {@code beanRegistrar()} often is, in each form Groovy compiles differently. Each is a call to
+ * {@code asType}, not a cast, and it declares the value as a {@code Closure} only when the compiler knows it
+ * is one: as an {@code Object} for a {@code def} variable or a method's result, and as a {@code Map} for a
+ * map literal, which becomes the interface through a JDK proxy as a closure does.
*/
class DynamicCoercionFixture {
- static IntUnaryOperator doubling() {
- { int operand -> operand * 2 } as IntUnaryOperator
+ static Closure doubling() {
+ { int value -> value * 2 }
}
+
+ static Object closureLiteral() {
+ { int value -> value * 2 } as ClosureLiteralCoercion
+ }
+
+ static Object typedClosure() {
+ Closure doubled = { int value -> value * 2 }
+ doubled as TypedClosureCoercion
+ }
+
+ static Object untypedClosure() {
+ def doubled = { int value -> value * 2 }
+ doubled as UntypedClosureCoercion
+ }
+
+ static Object closureResult() {
+ doubling() as ClosureResultCoercion
+ }
+
+ static Object mapLiteral() {
+ [apply: { int value -> value * 2 }] as MapLiteralCoercion
+ }
+}
+
+/** The same in a statically compiled class, where {@code as} is a call to {@code asType} as well. */
+@CompileStatic
+class StaticCoercionFixture {
+
+ static Object closureLiteral() {
+ { int value -> value * 2 } as StaticClosureLiteralCoercion
+ }
+
+ static Object mapLiteral() {
+ [apply: { int value -> value * 2 }] as StaticMapLiteralCoercion
+ }
+}
+
+/** What a coercion fixture turns a value into: one interface per form, so finding one proves that form was read. */
+interface ClosureLiteralCoercion {
+ int apply(int value)
+}
+
+/** See {@link ClosureLiteralCoercion}. */
+interface TypedClosureCoercion {
+ int apply(int value)
+}
+
+/** See {@link ClosureLiteralCoercion}. */
+interface UntypedClosureCoercion {
+ int apply(int value)
+}
+
+/** See {@link ClosureLiteralCoercion}. */
+interface ClosureResultCoercion {
+ int apply(int value)
+}
+
+/** See {@link ClosureLiteralCoercion}. */
+interface MapLiteralCoercion {
+ int apply(int value)
+}
+
+/** See {@link ClosureLiteralCoercion}. */
+interface StaticClosureLiteralCoercion {
+ int apply(int value)
+}
+
+/** See {@link ClosureLiteralCoercion}. */
+interface StaticMapLiteralCoercion {
+ int apply(int value)
}
/**
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
index 768e3988362..aa21bf5837a 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
@@ -20,7 +20,6 @@ package org.apache.grails.core.aot
import java.lang.reflect.Proxy
import java.util.function.IntBinaryOperator
-import java.util.function.IntUnaryOperator
import org.springframework.aot.hint.MemberCategory
import org.springframework.aot.hint.RuntimeHints
@@ -29,7 +28,9 @@ import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
import spock.lang.Shared
import spock.lang.Specification
+import grails.config.ConfigProperties
import grails.util.Environment
+import org.grails.config.PropertySourcesConfig
/**
* Covers what Groovy does reflectively on behalf of the framework's classes being possible in an
@@ -87,9 +88,35 @@ class BytecodeRuntimeHintsSpec extends Specification {
RuntimeHintsPredicates.proxies().forInterfaces(IntBinaryOperator).test(hints)
}
- void 'an interface a dynamically compiled class coerces a closure to with as can be proxied'() {
- expect: 'dynamic code makes the coercion a call to asType right after naming the interface, not a cast'
- RuntimeHintsPredicates.proxies().forInterfaces(IntUnaryOperator).test(hints)
+ void 'the interface #coercion is coerced to can be proxied'() {
+ when: 'the fixture runs the coercion, which is the code the hint is for'
+ def coerced = fixture.call()
+
+ then: 'Groovy makes a JDK proxy for it as the coercion runs'
+ Proxy.isProxyClass(coerced.getClass())
+ coerced.apply(21) == 42
+
+ and: 'the image is told to allow one, whatever the code declared the value as'
+ RuntimeHintsPredicates.proxies().forInterfaces(target).test(hints)
+
+ where:
+ coercion | fixture | target
+ 'a closure literal in dynamic code' | { DynamicCoercionFixture.closureLiteral() } | ClosureLiteralCoercion
+ 'a Closure variable in dynamic code' | { DynamicCoercionFixture.typedClosure() } | TypedClosureCoercion
+ 'a def variable holding a closure' | { DynamicCoercionFixture.untypedClosure() } | UntypedClosureCoercion
+ 'a method result that is a closure' | { DynamicCoercionFixture.closureResult() } | ClosureResultCoercion
+ 'a map literal in dynamic code' | { DynamicCoercionFixture.mapLiteral() } | MapLiteralCoercion
+ 'a closure literal in statically compiled code' | { StaticCoercionFixture.closureLiteral() } | StaticClosureLiteralCoercion
+ 'a map literal in statically compiled code' | { StaticCoercionFixture.mapLiteral() } | StaticMapLiteralCoercion
+ }
+
+ void 'the configuration can list its property names as properties'() {
+ when: 'the names are asked for, which turns a map of closures into an enumeration'
+ def names = new ConfigProperties(new PropertySourcesConfig('grails.fixture': 'value')).propertyNames()
+
+ then: 'Groovy makes a JDK proxy for it, which the image is told to allow'
+ Proxy.isProxyClass(names.getClass())
+ RuntimeHintsPredicates.proxies().forInterfaces(Enumeration).test(hints)
}
void 'a trait can be initialized by the classes implementing it'() {
@@ -168,15 +195,6 @@ class BytecodeRuntimeHintsSpec extends Specification {
ClosureCoercionFixture.sum(4) == 6
}
- void 'the dynamic coercion still makes a JDK proxy'() {
- when:
- def doubling = DynamicCoercionFixture.doubling()
-
- then: 'the fixture is the code the hint is for, so it has to do what it says'
- Proxy.isProxyClass(doubling.getClass())
- doubling.applyAsInt(21) == 42
- }
-
void 'the trait still initializes'() {
expect: 'the fixture is the code the hint is for, so it has to do what it says'
new GreeterFixture().greeting == 'hello'
diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index bf2ce62431c..94f2d79af28 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
@@ -115,7 +115,7 @@ Starting an application needs reflection the framework does on its own behalf, a
* the classes listed in `META-INF/grails.factories`, such as the artefact handlers;
* the beans the plugins declare, through a `BeanRegistrar` or the bean DSL, which are declared again as the application starts and created and wired from there;
* the artefacts the application holds -- including ones it did not write, such as the default URL mappings -- and the artefacts the plugins provide, such as the codecs;
-* what Groovy does reflectively even for statically compiled classes, in the framework and in the application's own packages: creating a Groovy enum's constants, initializing a trait from a class that implements it, and turning a closure into an interface, wherever statically compiled code does it and wherever dynamically compiled code names the interface with `as`;
+* what Groovy does reflectively even for statically compiled classes, in the framework and in the application's own packages: creating a Groovy enum's constants, initializing a trait from a class that implements it, and turning a closure or a map into an interface, wherever statically compiled code passes or assigns a closure to one and wherever any code names the interface with `as`, whatever it knows about the value;
* the build information that says which environment the application was packaged for, and the default validation messages.
The list covers starting the application. What a request reaches is still recorded, as described below, and that covers two things: the framework's own reflection along the request's path, and the reflection the application's own dynamically compiled code does. A call written without static compilation is resolved where it is made, against whatever it is made on, and only a run shows what that is. That includes a closure such code passes to a method taking an interface: the closure becomes that interface through a proxy, and nothing in the compiled call names which. Compiling the application's code statically, as a generated application's `Application` class is, takes its own calls out of what has to be recorded, but not the framework's reflection on a request's path.
From 1f0e69bdf7394990c48b686b1d02a7e877d7be7e Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Sat, 24 Oct 2026 08:17:50 -0700
Subject: [PATCH 37/39] Skip a sealed interface an as coercion names
Now that any `as` naming an interface is found, `value as SomeSealedInterface` registers a proxy for
it. The JDK refuses to proxy a sealed interface, so a value can only be coerced to one it already
implements, and the hint is of no use.
---
.../grails/core/aot/BytecodeRuntimeHints.java | 13 +++++++++++--
.../grails/core/aot/BytecodeFixtures.groovy | 19 +++++++++++++++++++
.../core/aot/BytecodeRuntimeHintsSpec.groovy | 12 ++++++++++++
3 files changed, 42 insertions(+), 2 deletions(-)
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
index 2d943e733db..450e0fd8ddd 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/BytecodeRuntimeHints.java
@@ -192,7 +192,7 @@ private static void read(Resource resource, Findings findings) {
/**
* The type, or none if it cannot be loaded here: registering a type that does not load fails the image
- * build, and a closure cast to an abstract class is not proxied by the JDK, so only an interface is.
+ * build.
*/
@Nullable
private static Class> load(String type, ClassLoader loader) {
@@ -240,6 +240,15 @@ private static boolean referencesLoad(Resource resource, ClassLoader loader) {
}
}
+ /**
+ * Whether the JDK can make a proxy of the type: an interface, and not a sealed one. A value coerced to an
+ * abstract class is not proxied by the JDK, and one coerced to a sealed interface it implements needs no
+ * proxy, since the JDK refuses to make one.
+ */
+ private static boolean isProxiable(Class> type) {
+ return type.isInterface() && !type.isSealed();
+ }
+
/** A method by its name and the names of its parameter types. */
private record MethodSignature(String name, List parameterTypes) {
}
@@ -273,7 +282,7 @@ private void register(RuntimeHints hints, ClassLoader loader) {
}
for (String type : coercedTo) {
Class> coerced = load(type, loader);
- if (coerced != null && coerced.isInterface()) {
+ if (coerced != null && isProxiable(coerced)) {
hints.proxies().registerJdkProxy(TypeReference.of(type));
}
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
index 0a861559c9d..dd6835686b5 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeFixtures.groovy
@@ -99,6 +99,25 @@ class StaticCoercionFixture {
}
}
+/**
+ * A value coerced with {@code as} to a sealed interface it already implements, which needs no proxy: the JDK
+ * refuses to proxy a sealed interface at all.
+ */
+class SealedCoercionFixture {
+
+ static Object permitted() {
+ new PermittedCoercion() as SealedCoercion
+ }
+}
+
+/** A sealed interface, and below it the one class it permits. */
+sealed interface SealedCoercion permits PermittedCoercion {
+}
+
+/** See {@link SealedCoercion}. */
+final class PermittedCoercion implements SealedCoercion {
+}
+
/** What a coercion fixture turns a value into: one interface per form, so finding one proves that form was read. */
interface ClosureLiteralCoercion {
int apply(int value)
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
index aa21bf5837a..2a6348ae838 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BytecodeRuntimeHintsSpec.groovy
@@ -110,6 +110,18 @@ class BytecodeRuntimeHintsSpec extends Specification {
'a map literal in statically compiled code' | { StaticCoercionFixture.mapLiteral() } | StaticMapLiteralCoercion
}
+ void 'a sealed interface named with as is not registered for a proxy'() {
+ given: 'one the JVM sees as sealed'
+ assert SealedCoercion.isSealed()
+
+ when: 'a value that already implements it is coerced to it'
+ def coerced = SealedCoercionFixture.permitted()
+
+ then: 'it needs no proxy, and the JDK refuses to make one for a sealed interface, so a hint is of no use'
+ coerced instanceof PermittedCoercion
+ !RuntimeHintsPredicates.proxies().forInterfaces(SealedCoercion).test(hints)
+ }
+
void 'the configuration can list its property names as properties'() {
when: 'the names are asked for, which turns a map of closures into an enumeration'
def names = new ConfigProperties(new PropertySourcesConfig('grails.fixture': 'value')).propertyNames()
From 6f481ef9b5a349184ff25dd9c78ab617022d8118 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Sat, 24 Oct 2026 08:27:04 -0700
Subject: [PATCH 38/39] Drop the as Runnable a shutdown hook applied to nothing
In `ShutdownOperations.addOperation { ... } as Runnable` the `as` binds to the call's void result,
so it coerced null and did nothing; the closure reaches addOperation as it is, being a Runnable
already. Now that any `as` naming an interface is registered for a proxy, it cost every image an
unused Runnable proxy hint.
The hook had no tests. The spec covers its lifecycle, which databases it shuts down, and that the
shutdown waits for the shutdown operations to run.
---
.../EmbeddedDatabaseShutdownHook.groovy | 2 +-
.../EmbeddedDatabaseShutdownHookSpec.groovy | 181 ++++++++++++++++++
2 files changed, 182 insertions(+), 1 deletion(-)
create mode 100644 grails-datasource/src/test/groovy/org/grails/plugins/datasource/EmbeddedDatabaseShutdownHookSpec.groovy
diff --git a/grails-datasource/src/main/groovy/org/grails/plugins/datasource/EmbeddedDatabaseShutdownHook.groovy b/grails-datasource/src/main/groovy/org/grails/plugins/datasource/EmbeddedDatabaseShutdownHook.groovy
index 7184511cba3..a12c7e4253e 100644
--- a/grails-datasource/src/main/groovy/org/grails/plugins/datasource/EmbeddedDatabaseShutdownHook.groovy
+++ b/grails-datasource/src/main/groovy/org/grails/plugins/datasource/EmbeddedDatabaseShutdownHook.groovy
@@ -123,6 +123,6 @@ class EmbeddedDatabaseShutdownHook implements SmartLifecycle, ApplicationContext
} finally {
try { connection?.close() } catch (ignored) {}
}
- } as Runnable
+ }
}
}
diff --git a/grails-datasource/src/test/groovy/org/grails/plugins/datasource/EmbeddedDatabaseShutdownHookSpec.groovy b/grails-datasource/src/test/groovy/org/grails/plugins/datasource/EmbeddedDatabaseShutdownHookSpec.groovy
new file mode 100644
index 00000000000..f4058ca082e
--- /dev/null
+++ b/grails-datasource/src/test/groovy/org/grails/plugins/datasource/EmbeddedDatabaseShutdownHookSpec.groovy
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.plugins.datasource
+
+import java.sql.Connection
+
+import javax.sql.DataSource
+
+import groovy.sql.Sql
+
+import org.springframework.context.support.GenericApplicationContext
+import org.springframework.jdbc.datasource.AbstractDataSource
+import org.springframework.jdbc.datasource.DriverManagerDataSource
+
+import org.grails.core.lifecycle.ShutdownOperations
+
+import spock.lang.Specification
+
+/**
+ * Covers the hook that shuts an embedded database down once the application's shutdown operations run.
+ */
+class EmbeddedDatabaseShutdownHookSpec extends Specification {
+
+ GenericApplicationContext context = new GenericApplicationContext()
+
+ EmbeddedDatabaseShutdownHook hook = new EmbeddedDatabaseShutdownHook()
+
+ void setup() {
+ ShutdownOperations.resetOperations()
+ hook.applicationContext = context
+ }
+
+ void cleanup() {
+ ShutdownOperations.resetOperations()
+ context.close()
+ }
+
+ void "an embedded database is shut down when the shutdown operations run, not when the hook stops"() {
+ given: 'an in-memory database kept open until it is shut down, holding a table'
+ def dataSource = new DriverManagerDataSource('jdbc:h2:mem:embeddedShutdownHook;DB_CLOSE_DELAY=-1')
+ context.registerBean('dataSource', DataSource, { dataSource })
+ context.refresh()
+ new Sql(dataSource).execute('CREATE TABLE book (title VARCHAR(50))')
+
+ when:
+ hook.start()
+ hook.stop()
+
+ then: 'stopping only schedules the shutdown'
+ tableExists(dataSource)
+
+ when:
+ ShutdownOperations.runOperations()
+
+ then: 'the database was shut down, so the next connection opens an empty one'
+ !tableExists(dataSource)
+ }
+
+ void "a database at #url is #treatment"() {
+ given:
+ def dataSource = new CountingDataSource(url: url)
+ context.registerBean('dataSource', DataSource, { dataSource })
+ context.refresh()
+
+ when:
+ hook.start()
+ hook.stop()
+
+ then: 'a connection is taken only to shut a database down'
+ dataSource.connections == connections
+
+ where:
+ url | connections
+ 'jdbc:h2:mem:shutdownHook' | 1
+ 'jdbc:h2:file:/tmp/shutdownHook' | 1
+ 'jdbc:hsqldb:mem:shutdownHook' | 1
+ 'jdbc:h2:tcp://localhost/db' | 0
+ 'jdbc:h2:ssl://localhost/db' | 0
+ 'jdbc:hsqldb:hsql://localhost/db' | 0
+ 'jdbc:hsqldb:http://localhost/db' | 0
+ 'jdbc:postgresql://localhost/db' | 0
+ null | 0
+
+ treatment = connections ? 'shut down, being embedded' : 'left alone'
+ }
+
+ void "a data source without a url is left alone"() {
+ given:
+ def dataSource = new UrlLessDataSource()
+ context.registerBean('dataSource', DataSource, { dataSource })
+ context.refresh()
+
+ when:
+ hook.start()
+ hook.stop()
+
+ then:
+ dataSource.connections == 0
+ }
+
+ void "it runs as a lifecycle bean stopped after every other"() {
+ given:
+ context.refresh()
+ boolean calledBack = false
+
+ expect:
+ !hook.running
+ hook.autoStartup
+ hook.phase == Integer.MIN_VALUE
+
+ when:
+ hook.start()
+
+ then:
+ hook.running
+
+ when:
+ hook.stop { calledBack = true }
+
+ then:
+ !hook.running
+ calledBack
+ }
+
+ private static boolean tableExists(DataSource dataSource) {
+ new Sql(dataSource).firstRow(
+ "SELECT COUNT(*) AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'BOOK'").found > 0
+ }
+
+ /** A data source that counts the connections taken from it, and opens none. */
+ static class CountingDataSource extends AbstractDataSource {
+
+ String url
+
+ int connections
+
+ @Override
+ Connection getConnection() {
+ connections++
+ null
+ }
+
+ @Override
+ Connection getConnection(String username, String password) {
+ getConnection()
+ }
+ }
+
+ /** The same, without a url property. */
+ static class UrlLessDataSource extends AbstractDataSource {
+
+ int connections
+
+ @Override
+ Connection getConnection() {
+ connections++
+ null
+ }
+
+ @Override
+ Connection getConnection(String username, String password) {
+ getConnection()
+ }
+ }
+}
From 68fa0b8bb8eabbcae7b3ec7a4acada43f496c019 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 29 Oct 2026 08:23:21 -0700
Subject: [PATCH 39/39] Keep the constructor hint of a Spring class a registrar
declares
A registrar's beans are left out of the generated code and declared again
as the application starts, so Spring creates them through their
constructor whatever their package. A Spring class is now treated as
created by the generated code only when its definition is not a
registrar's; an image built without the hint failed to start with
"No default constructor found".
---
...BeanFactoryInitializationAotProcessor.java | 12 ++++++++---
...ctoryInitializationAotProcessorSpec.groovy | 20 +++++++++++++++++++
2 files changed, 29 insertions(+), 3 deletions(-)
diff --git a/grails-core/src/main/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessor.java b/grails-core/src/main/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessor.java
index bf6328eb953..86f75e2f32d 100644
--- a/grails-core/src/main/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessor.java
+++ b/grails-core/src/main/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessor.java
@@ -39,6 +39,7 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
+import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
@@ -65,7 +66,7 @@
* built by a supplier and declared as an interface hides the class whose members need injecting; those
* processors then inject every bean, including the ones the generated code already injected, and do it
* reflectively. Only the annotated members of Spring's beans are registered: creating them is the generated
- * code's business.
+ * code's business, except for the ones a registrar declares, which the generated code leaves out.
*
* @since 9.0
*/
@@ -102,7 +103,7 @@ public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableL
/**
* The class of every bean, and how much of it is reached reflectively: a bean is created through its
* constructor unless a supplier or a factory method creates it, and the product of a factory method, like
- * a Spring bean, only has its annotated members reached.
+ * a Spring bean the generated code creates, only has its annotated members reached.
*/
private Map, Integer> beanClassesOf(ConfigurableListableBeanFactory beanFactory) {
Map, Integer> beanClasses = new LinkedHashMap<>();
@@ -130,7 +131,7 @@ private Map, Integer> beanClassesOf(ConfigurableListableBeanFactory bea
if (beanClass == null) {
continue;
}
- if (beanClass.getName().startsWith(SPRING_PACKAGE)) {
+ if (beanClass.getName().startsWith(SPRING_PACKAGE) && !isLeftOutOfGeneration(beanDefinition)) {
access = INJECTED;
}
beanClasses.merge(beanClass, access, Math::max);
@@ -138,6 +139,11 @@ private Map, Integer> beanClassesOf(ConfigurableListableBeanFactory bea
return beanClasses;
}
+ /** A registrar's bean: the generated code does not create it, and the registrar declares it again. */
+ private static boolean isLeftOutOfGeneration(AbstractBeanDefinition beanDefinition) {
+ return Boolean.TRUE.equals(beanDefinition.getAttribute(BeanRegistrationAotProcessor.IGNORE_REGISTRATION_ATTRIBUTE));
+ }
+
/** What a factory method creates, as far as it can be told without calling it. */
@Nullable
private static Class> productOf(ConfigurableListableBeanFactory beanFactory, String name) {
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
index fb55681de37..bd4384f9eb0 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
@@ -36,6 +36,7 @@ import org.springframework.context.support.GenericApplicationContext
import org.springframework.scheduling.annotation.ProxyAsyncConfiguration
import org.springframework.core.env.Environment
import org.springframework.javapoet.ClassName
+import org.springframework.util.StopWatch
import spock.lang.Specification
/**
@@ -141,6 +142,17 @@ class BeanReflectionBeanFactoryInitializationAotProcessorSpec extends Specificat
!registered(hints, ProxyAsyncConfiguration, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)
}
+ void 'a Spring class a registrar declares by class can be created'() {
+ given: 'a registrar bean is left out of the generated code, so Spring creates it as the registrar declared it'
+ register(new SpringClassRegistrar())
+
+ when:
+ def hints = hints()
+
+ then:
+ registered(hints, StopWatch, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS)
+ }
+
void 'the product of a factory method has its injection points reached'() {
given: 'a bean a factory method creates'
context.registerBeanDefinition('produced', new RootBeanDefinition(FactoryFixture).tap {
@@ -171,6 +183,14 @@ class BeanReflectionBeanFactoryInitializationAotProcessorSpec extends Specificat
}
}
+ static class SpringClassRegistrar implements BeanRegistrar {
+
+ @Override
+ void register(BeanRegistry registry, Environment environment) {
+ registry.registerBean('watch', StopWatch)
+ }
+ }
+
static class DeclaredByClassFixture {
String name