You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@grails.apache.org by "codeconsole (via GitHub)" <gi...@apache.org> on 2026/07/19 21:10:42 UTC
[PR] [Spike] @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
codeconsole opened a new pull request, #16019:
URL: https://github.com/apache/grails-core/pull/16019
## Summary
This is a proof-of-concept / discussion-stage spike, **not a request to merge as-is**. It explores whether Grails-authored bean wiring can get `doWithSpring()`-style DSL ergonomics while compiling down to a genuine Spring Boot `@AutoConfiguration` class — no closures, no custom runtime, nothing but real `@Bean` methods in the compiled bytecode.
Two pieces:
1. **`grails-beans-dsl`** — a `@GrailsBeans` annotation + local Groovy AST transformation (`GrailsBeansASTTransformation`) that rewrites a `beans = { bean(Type[, "name"]) { ... } }` closure into public `@Bean` factory methods, with `.conditionalOnMissingBean(Type...)` chaining and typed closure parameters becoming constructor-style-injected method parameters.
2. **`org.apache.grails.buildsrc.autoconfiguration-imports`** — a new build-logic convention plugin that generates `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` by scanning a module's own compiled classes for `@AutoConfiguration`, the same way `META-INF/grails-plugin.xml` is already generated from scanned `*GrailsPlugin` classes elsewhere in this build — so the imports file never has to be hand-maintained.
## Why this, given `beanRegistrar()` already exists
`Plugin.beanRegistrar()` (#15994) plus the before-autoconfiguration retiming (#15934) already give Grails a Spring-native, statically-compilable bean-registration mechanism that runs before Boot evaluates its `@ConditionalOnMissingBean` defaults. That solves the *coarse* half of what this spike targets.
It does **not** solve the *fine-grained* half: `beanRegistrar()` output is inserted as a single hard cut point ahead of *all* Boot auto-configuration, ordered only relative to other Grails plugins by name — it has no way to express "run before this specific `@AutoConfiguration` but after that one," the way `@AutoConfiguration(before = ..., after = ...)` lets a real autoconfiguration class do against *any* other autoconfiguration on the classpath, Grails-authored or third-party. That's the open question this spike is raising: is it worth Grails-authored beans compiling down to genuine `@AutoConfiguration` classes so they can fully participate in Boot's own ordering graph, with DSL ergonomics comparable to `beanRegistrar()`?
## Usage example
Author:
```groovy
package myapp
import org.grails.compiler.beans.GrailsBeans
import org.springframework.boot.autoconfigure.AutoConfiguration
@GrailsBeans
@AutoConfiguration
class MyBeans {
def beans = {
bean(Greeter, 'greeter') {
new Greeter('hello')
}
bean(FancyGreeter, 'fancyGreeter').conditionalOnMissingBean(FancyGreeter) {
new FancyGreeter()
}
bean(LoudGreeter, 'loudGreeter') { Greeter greeter ->
new LoudGreeter(greeter)
}
}
}
```
Compiles to the equivalent of (verified directly via `javap` — zero closures survive into the bytecode):
```java
@AutoConfiguration
public class MyBeans {
@Bean("greeter")
public Greeter greeter() { return new Greeter("hello"); }
@Bean("fancyGreeter")
@ConditionalOnMissingBean(FancyGreeter.class)
public FancyGreeter fancyGreeter() { return new FancyGreeter(); }
@Bean("loudGreeter")
public LoudGreeter loudGreeter(Greeter greeter) { return new LoudGreeter(greeter); }
}
```
Register it by applying the new convention plugin (see `grails-beans-dsl-example/build.gradle`):
```groovy
plugins {
id 'org.apache.grails.buildsrc.autoconfiguration-imports'
}
```
which scans the module's compiled output and writes `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` automatically at build time.
`grails-beans-dsl-example/src/test/groovy/beandsl/example/ExampleBeansAutoDiscoverySpec.groovy` is the end-to-end proof this actually works as a whole pipeline: it boots a bare `@EnableAutoConfiguration` application with **zero explicit reference** to `ExampleBeans`, and the beans are still discovered and correctly wired — purely from the generated imports file.
## What's here
- `grails-beans-dsl` — the annotation + transform, with unit tests that compile fixture sources and inspect the generated bytecode directly.
- `grails-beans-dsl-example` — a worked example (`Greeter` / `FancyGreeter` / `LoudGreeter`), including the conditional-back-off test and the auto-discovery end-to-end test above.
- `build-logic` — the new `autoconfiguration-imports` convention plugin, with its own fixture-compiling unit tests.
## Test plan
- [x] `:grails-beans-dsl:test` — AST transform unit tests
- [x] `:grails-beans-dsl-example:test` — conditional back-off + end-to-end classpath auto-discovery
- [x] `:build-logic:test` / `:build-logic:check` — imports-generation task unit tests
- [x] `checkstyleMain` / `codenarcMain` clean on all new source
- [ ] Full-repo `aggregateViolations` / RAT / SBOM / doc-guide integration — deliberately **not** run; this is a discussion-stage spike, not merge-ready
## Deliberately not done yet (first-look spike)
- No `grails-doc` guide chapter
- DSL surface is intentionally narrow — single-type conditional only, no property values / destroy methods / parent bean definitions (comparable limitations to `BeanRegistry.Spec`)
- Not reconciled with `beanRegistrar()` beyond the comparison above — looking for feedback on whether the fine-grained ordering capability is worth a second bean-wiring mechanism, or whether that capability should be added to `beanRegistrar()` / the plugin ordering system instead
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5017611254
## [Codecov](https://app.codecov.io/gh/apache/grails-core/pull/16019?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `84.00000%` with `16 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 51.4755%. Comparing base ([`ce1884f`](https://app.codecov.io/gh/apache/grails-core/commit/ce1884f8f7b26b92e3220df4601f9636564106ed?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`a8a12d5`](https://app.codecov.io/gh/apache/grails-core/commit/a8a12d5d5a92ae469406cbceba9aaff6cd4704d0?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/grails-core/pull/16019?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...s/compiler/beans/GrailsBeansASTTransformation.java](https://app.codecov.io/gh/apache/grails-core/pull/16019?src=pr&el=tree&filepath=grails-beans-dsl%2Fsrc%2Fmain%2Fjava%2Forg%2Fgrails%2Fcompiler%2Fbeans%2FGrailsBeansASTTransformation.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Z3JhaWxzLWJlYW5zLWRzbC9zcmMvbWFpbi9qYXZhL29yZy9ncmFpbHMvY29tcGlsZXIvYmVhbnMvR3JhaWxzQmVhbnNBU1RUcmFuc2Zvcm1hdGlvbi5qYXZh) | 81.8182% | [7 Missing and 9 partials :warning: ](https://app.codecov.io/gh/apache/grails-core/pull/16019?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
[](https://app.codecov.io/gh/apache/grails-core/pull/16019?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
```diff
@@ Coverage Diff @@
## 8.0.x #16019 +/- ##
==================================================
+ Coverage 51.4393% 51.4755% +0.0361%
- Complexity 17724 17757 +33
==================================================
Files 2039 2044 +5
Lines 95497 95597 +100
Branches 16564 16582 +18
==================================================
+ Hits 49123 49209 +86
- Misses 39076 39080 +4
- Partials 7298 7308 +10
```
| [Files with missing lines](https://app.codecov.io/gh/apache/grails-core/pull/16019?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [...rc/main/groovy/beandsl/example/ExampleBeans.groovy](https://app.codecov.io/gh/apache/grails-core/pull/16019?src=pr&el=tree&filepath=grails-beans-dsl-example%2Fsrc%2Fmain%2Fgroovy%2Fbeandsl%2Fexample%2FExampleBeans.groovy&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Z3JhaWxzLWJlYW5zLWRzbC1leGFtcGxlL3NyYy9tYWluL2dyb292eS9iZWFuZHNsL2V4YW1wbGUvRXhhbXBsZUJlYW5zLmdyb292eQ==) | `100.0000% <100.0000%> (ø)` | |
| [...rc/main/groovy/beandsl/example/FancyGreeter.groovy](https://app.codecov.io/gh/apache/grails-core/pull/16019?src=pr&el=tree&filepath=grails-beans-dsl-example%2Fsrc%2Fmain%2Fgroovy%2Fbeandsl%2Fexample%2FFancyGreeter.groovy&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Z3JhaWxzLWJlYW5zLWRzbC1leGFtcGxlL3NyYy9tYWluL2dyb292eS9iZWFuZHNsL2V4YW1wbGUvRmFuY3lHcmVldGVyLmdyb292eQ==) | `100.0000% <100.0000%> (ø)` | |
| [...ple/src/main/groovy/beandsl/example/Greeter.groovy](https://app.codecov.io/gh/apache/grails-core/pull/16019?src=pr&el=tree&filepath=grails-beans-dsl-example%2Fsrc%2Fmain%2Fgroovy%2Fbeandsl%2Fexample%2FGreeter.groovy&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Z3JhaWxzLWJlYW5zLWRzbC1leGFtcGxlL3NyYy9tYWluL2dyb292eS9iZWFuZHNsL2V4YW1wbGUvR3JlZXRlci5ncm9vdnk=) | `100.0000% <100.0000%> (ø)` | |
| [...src/main/groovy/beandsl/example/LoudGreeter.groovy](https://app.codecov.io/gh/apache/grails-core/pull/16019?src=pr&el=tree&filepath=grails-beans-dsl-example%2Fsrc%2Fmain%2Fgroovy%2Fbeandsl%2Fexample%2FLoudGreeter.groovy&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Z3JhaWxzLWJlYW5zLWRzbC1leGFtcGxlL3NyYy9tYWluL2dyb292eS9iZWFuZHNsL2V4YW1wbGUvTG91ZEdyZWV0ZXIuZ3Jvb3Z5) | `100.0000% <100.0000%> (ø)` | |
| [...s/compiler/beans/GrailsBeansASTTransformation.java](https://app.codecov.io/gh/apache/grails-core/pull/16019?src=pr&el=tree&filepath=grails-beans-dsl%2Fsrc%2Fmain%2Fjava%2Forg%2Fgrails%2Fcompiler%2Fbeans%2FGrailsBeansASTTransformation.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Z3JhaWxzLWJlYW5zLWRzbC9zcmMvbWFpbi9qYXZhL29yZy9ncmFpbHMvY29tcGlsZXIvYmVhbnMvR3JhaWxzQmVhbnNBU1RUcmFuc2Zvcm1hdGlvbi5qYXZh) | `81.8182% <81.8182%> (ø)` | |
... and [3 files with indirect coverage changes](https://app.codecov.io/gh/apache/grails-core/pull/16019/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
</details>
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3679574264
##########
grails-core/build.gradle:
##########
@@ -51,6 +51,8 @@ dependencies {
api 'jakarta.persistence:jakarta.persistence-api'
api 'jakarta.annotation:jakarta.annotation-api'
+ api project(':grails-beans-dsl')
Review Comment:
Resolved by `138d014236` along the lines of your follow-up: this `api` is the one declaration, and it now carries a comment recording *why* — that `compileBeansDsl` loads the transform reflectively and returns silently when absent, so this line is what makes the implicit `def beans = { }` convention reach a third-party plugin author.
I did not change `@GrailsBeans` to `CLASS` retention. It is a reasonable point that nothing reads it at runtime, but it is a separate question from the scope story and I would rather not fold an unrelated retention change into this PR. Say the word if you want it here.
##########
grails-core/src/main/groovy/org/grails/compiler/injection/GlobalGrailsClassInjectorTransformation.groovy:
##########
@@ -179,6 +188,44 @@ class GlobalGrailsClassInjectorTransformation implements ASTTransformation, Comp
/**
* @return {@code true} when the {@code grails.isolated.build} system property is {@code true}.
*/
+ /**
+ * Compiles a plugin descriptor's or application class's {@code beans} closure into {@code @Bean}
+ * factory methods, so {@code @GrailsBeans} does not have to be written out - the {@code beans}
+ * property is a convention here in the same way {@code doWithSpring} and {@code watchedResources}
+ * already are.
+ *
+ * <p>The transformation is invoked directly rather than by adding the annotation: annotation-driven
+ * transformations are collected during semantic analysis, so an annotation added at
+ * {@code CANONICALIZATION} would never fire. A class that already declares {@code @GrailsBeans}
+ * is skipped, since its own transformation has run; a class without a {@code beans} property is
+ * skipped too, which is every plugin that does not use the DSL.</p>
+ */
+ private void compileBeansDsl(ClassNode classNode, SourceUnit source) {
+ if (classNode.getProperty(BEANS_PROPERTY) == null) {
+ return
+ }
+ if (!classNode.getAnnotations(GRAILS_BEANS_ANNOTATION).isEmpty()) {
+ return
+ }
+
+ ASTTransformation transformation
+ try {
+ transformation = (ASTTransformation) getClass().classLoader
+ .loadClass('org.grails.compiler.beans.GrailsBeansASTTransformation')
+ .getDeclaredConstructor()
+ .newInstance()
+ }
+ catch (ClassNotFoundException ignored) {
Review Comment:
Both addressed in `94e25dee20`.
The silent branch now records why it is allowed to be silent — it is unreachable only because `grails-core` declares the module `api`, and narrowing that scope would turn it into a live path where a DSL-shaped block registers nothing and reports nothing.
On the second: I narrowed the trigger rather than documenting the break. The implicit path now requires a closure whose every top-level statement is rooted in a `bean`/`field`/`method` call, so a pre-existing descriptor with `def beans = [...]`, or a closure of something else, is left alone. Writing `@GrailsBeans` explicitly still opts in to the strict errors, which is right where the author has said what they mean. An empty block is still claimed, so both spellings agree.
Three tests: a Map-valued property, a non-DSL closure, and a DSL-shaped one.
##########
settings.gradle:
##########
@@ -107,6 +107,9 @@ def skipMicronautProjects = explicitlySkipMicronaut || (!buildJdkSupportsMicrona
include(
'grails-bootstrap',
+ 'grails-beans-dsl',
+ 'grails-beans-dsl-example',
+ 'grails-beans-dsl-plugin-example',
Review Comment:
Drift, not a decision — thank you for checking rather than assuming. Both moved under `grails-test-examples/` in `0224df0ecd`, per the table in your later comment.
Your point that they are more than samples is taken: all 7 specs run at the new locations, `FarewellGrailsPluginAutoDiscoverySpec` included. And since that spec now sits outside core-only CI, the `autoconfiguration-imports` plugin gained a production consumer (`grails-databinding`) so that coverage is not the only thing exercising it.
##########
grails-core/build.gradle:
##########
@@ -51,6 +51,8 @@ dependencies {
api 'jakarta.persistence:jakarta.persistence-api'
api 'jakarta.annotation:jakarta.annotation-api'
+ api project(':grails-beans-dsl')
Review Comment:
Agreed, and it stays. It now carries a comment recording the reasoning you set out here — that `compileBeansDsl` loads the transform reflectively and returns silently when it is absent, so this `api` is what makes the implicit `def beans = { }` convention reach a third-party plugin author (`138d014236`).
The other seven are deleted, and each removal was verified by its module's generated sibling class rather than by the build merely succeeding — see my reply on `grails-cache/build.gradle`.
##########
grails-cache/build.gradle:
##########
@@ -49,6 +49,7 @@ dependencies {
api "org.codehaus.gpars:gpars:$gparsVersion"
api "com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:$concurrentlinkedhashmapLruVersion"
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`.
Worth recording how that was checked, because compiling is *not* sufficient evidence here:
`compileBeansDsl` fails silently, so a module that lost the transform would still compile and
simply leave its `beans` block as an untouched property. Each of the seven was verified by its
generated sibling class existing, with forced no-cache recompiles of `grails-i18n` and
`grails-url-mappings`, which reach `grails-core` only transitively through `grails-web-core`.
The other six are `grails-databinding`, `grails-domain-class`, `grails-i18n`,
`grails-url-mappings`, `grails-sitemesh3` and `grails-mail`.
##########
grails-databinding/build.gradle:
##########
@@ -38,6 +38,7 @@ dependencies {
implementation platform(project(':grails-bom'))
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`, along with the other six. See my reply on `grails-cache/build.gradle` for how each removal was verified — compiling is not sufficient evidence, since `compileBeansDsl` fails silently, so `grails-databinding`'s generated sibling class was checked instead.
##########
grails-domain-class/build.gradle:
##########
@@ -38,6 +38,7 @@ dependencies {
implementation platform(project(':grails-bom'))
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`, along with the other six. See my reply on `grails-cache/build.gradle` for how each removal was verified — compiling is not sufficient evidence, since `compileBeansDsl` fails silently, so `grails-domain-class`'s generated sibling class was checked instead.
##########
grails-i18n/build.gradle:
##########
@@ -41,6 +41,8 @@ dependencies {
api project(':grails-web-core')
api 'org.apache.groovy:groovy'
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`, along with the other six. See my reply on `grails-cache/build.gradle` for how each removal was verified — compiling is not sufficient evidence, since `compileBeansDsl` fails silently, so `grails-i18n`'s generated sibling class was checked instead.
##########
grails-url-mappings/build.gradle:
##########
@@ -43,6 +43,8 @@ dependencies {
api 'org.apache.groovy:groovy'
api 'org.springframework.boot:spring-boot-servlet'
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`, along with the other six. See my reply on `grails-cache/build.gradle` for how each removal was verified — compiling is not sufficient evidence, since `compileBeansDsl` fails silently, so `grails-url-mappings`'s generated sibling class was checked instead.
##########
grails-gsp/grails-sitemesh3/build.gradle:
##########
@@ -52,6 +52,7 @@ dependencies {
api project(':grails-core')
implementation 'org.apache.groovy:groovy'
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`, along with the other six. See my reply on `grails-cache/build.gradle` for how each removal was verified — compiling is not sufficient evidence, since `compileBeansDsl` fails silently, so `grails-sitemesh3`'s generated sibling class was checked instead.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5017830630
## ✅ All tests passed ✅
🏷️ Commit: a8a12d5d5a92ae469406cbceba9aaff6cd4704d0
▶️ Tests: 56408 executed
⚪️ Checks: 59/59 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3705736464
##########
grails-doc/src/en/guide/conf/applicationClass/applicationLifeCycle.adoc:
##########
@@ -34,3 +34,5 @@ class Application extends GrailsAutoConfiguration {
...
}
----
+
+The `Application` class can also define its beans at compile time instead, by annotating it with `@GrailsBeans` — see link:spring.html#springdslAdditional[Configuring Additional Beans].
Review Comment:
Reworded, and added a test for the Application path, which had none.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3671179772
##########
grails-beans-dsl/build.gradle:
##########
@@ -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.
+ */
+
+plugins {
+ id 'groovy'
+ id 'java-library'
+ id 'org.apache.grails.buildsrc.properties'
+ id 'org.apache.grails.buildsrc.dependency-validator'
+ id 'org.apache.grails.buildsrc.compile'
+ id 'org.apache.grails.buildsrc.publish'
+ id 'org.apache.grails.buildsrc.sbom'
+ id 'org.apache.grails.buildsrc.vulnerability-scan'
+ id 'org.apache.grails.gradle.grails-code-style'
+ id 'org.apache.grails.gradle.grails-jacoco'
+}
+
+version = projectVersion
+group = 'org.apache.grails'
Review Comment:
This should be a nested group — `org.apache.grails.beandsl` rather than flat `org.apache.grails`.
The repo already partitions published coordinates this way, including for single-module projects, so there is direct precedent:
| group | example |
| --- | --- |
| `org.apache.grails.data` | `grails-datastore-core`, `grails-data-simple`, … |
| `org.apache.grails.web` | `grails-web-core`, `grails-web-mvc`, `grails-encoder`, … |
| `org.apache.grails.testing` | `grails-testing-support-core`, `grails-test-suite-*`, … |
| `org.apache.grails.events` / `.async` / `.forge` / `.gradle` | multi-module |
| `org.apache.grails.i18n` / `.databinding` / `.codecs` / `.common` / `.bootstrap` | **single-module** |
Since the DSL is intended to be on every project's classpath by default (via `grails-core`'s `api`), giving it its own namespace matches the project's decision for internal vs external includes.
Worth checking the knock-on: `gradle/publish-root-config.gradle` gates on project *name*, so that list is unaffected, but any BOM constraint or documentation that spells out the coordinates needs to follow the new group.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5019242526
## ✅ All tests passed ✅
🏷️ Commit: 79b2f3f15837ab08f11eca232f21f0459ef4ac05
▶️ Tests: 45818 executed
⚪️ Checks: 59/59 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5066126555
The `grails-sitemesh3` conversion (53dcb874db) follows the same pattern, and drove one more DSL capability: `.staticMethod()` (5450dffcfe), which generates a `static` `@Bean` factory method — required for the two view-resolver post-processor beans, since a `BeanFactoryPostProcessor`/`BeanPostProcessor` bean must be creatable without instantiating its declaring configuration class. Imports and comments are trimmed here; each linked filename is the verbatim, commit-pinned source.
Before, [`Sitemesh3AutoConfiguration.groovy`](https://github.com/codeconsole/grails-core/blob/5450dffcfe6bcc1c38ee30b8102f5492f976a4bc/grails-gsp/grails-sitemesh3/src/main/groovy/org/grails/plugins/sitemesh3/Sitemesh3AutoConfiguration.groovy#L19-L131) (since deleted):
```groovy
@CompileStatic
@AutoConfiguration
@AutoConfigureAfter(name = 'org.springframework.boot.webmvc.autoconfigure.DispatcherServletAutoConfiguration')
@AutoConfigureBefore(name = 'org.sitemesh.autoconfigure.SiteMeshViewResolverAutoConfiguration')
@ConditionalOnClass(SiteMeshViewResolverBeanPostProcessor)
@ConditionalOnProperty(name = 'sitemesh.integration', havingValue = 'view-resolver', matchIfMissing = true)
class Sitemesh3AutoConfiguration {
@Bean
@ConditionalOnMissingBean(SiteMeshViewResolverPostProcessor)
static Sitemesh3ViewResolverDefinitionPostProcessor siteMeshViewResolverPostProcessor() {
new Sitemesh3ViewResolverDefinitionPostProcessor()
}
@Bean
@ConditionalOnMissingBean(SiteMeshViewResolverBeanPostProcessor)
static GrailsSiteMeshViewResolverBeanPostProcessor siteMeshViewResolverBeanPostProcessor() {
new GrailsSiteMeshViewResolverBeanPostProcessor()
}
@Bean
@ConditionalOnBean(DispatcherServlet)
@ConditionalOnMissingBean(name = 'contentProcessor')
CaptureAwareContentProcessor contentProcessor() {
new CaptureAwareContentProcessor()
}
@Bean
@ConditionalOnBean(DispatcherServlet)
@ConditionalOnMissingBean(name = 'decoratorSelector')
Sitemesh3LayoutFinder decoratorSelector(ObjectProvider<GrailsConventionGroovyPageLocator> groovyPageLocator,
GrailsApplication grailsApplication) {
Config config = grailsApplication.config
Environment env = Environment.current
boolean developmentMode = Metadata.current.isDevelopmentEnvironmentAvailable()
boolean reloadEnabled = env.isReloadEnabled() ||
config.getProperty('grails.gsp.enable.reload', Boolean, false) ||
(developmentMode && env == Environment.DEVELOPMENT)
String defaultLayout = config.getProperty('grails.sitemesh.default.layout') ?:
config.getProperty('grails.views.layout.default')
Sitemesh3LayoutFinder finder = new Sitemesh3LayoutFinder(groovyPageLocator.getIfAvailable())
finder.gspReloadEnabled = reloadEnabled
finder.defaultDecoratorName = defaultLayout ?: null
finder.layoutCacheExpirationMillis = config.getProperty('grails.sitemesh.layout.cache.interval', Long, 5000L)
return finder
}
}
```
After — [`Sitemesh3GrailsPlugin.groovy`](https://github.com/codeconsole/grails-core/blob/53dcb874db7621286d37471412cab288990c9eef/grails-gsp/grails-sitemesh3/src/main/groovy/org/grails/plugins/sitemesh3/Sitemesh3GrailsPlugin.groovy#L19-L162)'s class declaration and `beans` block (the rest of the file — `beanRegistrar()`, the plugin metadata it already had — is untouched; the design documentation from the deleted class's javadoc moved onto the plugin):
```groovy
@CompileStatic
@GrailsBeans
@AutoConfiguration
@AutoConfigureAfter(name = 'org.springframework.boot.webmvc.autoconfigure.DispatcherServletAutoConfiguration')
@AutoConfigureBefore(name = 'org.sitemesh.autoconfigure.SiteMeshViewResolverAutoConfiguration')
@ConditionalOnClass(SiteMeshViewResolverBeanPostProcessor)
@ConditionalOnProperty(name = 'sitemesh.integration', havingValue = 'view-resolver', matchIfMissing = true)
class Sitemesh3GrailsPlugin extends Plugin {
def grailsVersion = '7.0.0-SNAPSHOT > *'
def title = 'SiteMesh 3'
def author = 'Scott Murphy'
def authorEmail = ''
def description = 'Provides GSP layout decoration using SiteMesh 3'
def profiles = ['web']
def license = 'APACHE'
def developers = [[name: 'Scott Murphy']]
def loadBefore = ['groovyPages']
def providedArtefacts = [
RenderSitemeshTagLib,
Sitemesh3LayoutTagLib,
]
def beans = {
bean('siteMeshViewResolverPostProcessor', Sitemesh3ViewResolverDefinitionPostProcessor).staticMethod().conditionalOnMissingBean(SiteMeshViewResolverPostProcessor) {
new Sitemesh3ViewResolverDefinitionPostProcessor()
}
bean('siteMeshViewResolverBeanPostProcessor', GrailsSiteMeshViewResolverBeanPostProcessor).staticMethod().conditionalOnMissingBean(SiteMeshViewResolverBeanPostProcessor) {
new GrailsSiteMeshViewResolverBeanPostProcessor()
}
bean('contentProcessor', CaptureAwareContentProcessor).annotate(ConditionalOnBean, value: DispatcherServlet).conditionalOnMissingBeanName() {
new CaptureAwareContentProcessor()
}
bean('decoratorSelector', Sitemesh3LayoutFinder).annotate(ConditionalOnBean, value: DispatcherServlet).conditionalOnMissingBeanName() { ObjectProvider<GrailsConventionGroovyPageLocator> groovyPageLocator, GrailsApplication grailsApplication ->
Config config = grailsApplication.config
grails.util.Environment env = grails.util.Environment.current
boolean developmentMode = Metadata.current.isDevelopmentEnvironmentAvailable()
boolean reloadEnabled = env.isReloadEnabled() ||
config.getProperty('grails.gsp.enable.reload', Boolean, false) ||
(developmentMode && env == grails.util.Environment.DEVELOPMENT)
String defaultLayout = config.getProperty('grails.sitemesh.default.layout') ?:
config.getProperty('grails.views.layout.default')
Sitemesh3LayoutFinder finder = new Sitemesh3LayoutFinder(groovyPageLocator.getIfAvailable())
finder.gspReloadEnabled = reloadEnabled
finder.defaultDecoratorName = defaultLayout ?: null
finder.layoutCacheExpirationMillis = config.getProperty('grails.sitemesh.layout.cache.interval', Long, 5000L)
return finder
}
}
```
The generated sibling regains the exact `Sitemesh3AutoConfiguration` class identity, so the module's `AutoConfiguration.imports` entry is untouched, and the class-level ordering and gating annotations (`@AutoConfigureAfter`/`Before` by name, `@ConditionalOnClass`, `@ConditionalOnProperty`) move onto it at compile time. The pre-existing `Sitemesh3AutoConfigurationSpec` passes unmodified — including its direct static invocations of the two post-processor factory methods — and javap confirms both methods are `static` and the class is fully statically compiled. The `grails-mail` conversion (6e4a52013d) is on the branch as well, exercising parameter-level `@Autowired(required = false)`/`@Qualifier` annotations carrying through closure parameters.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5094650830
The `grails-cache` conversion (311fb9a959), same pattern. This is the first one where the generated sibling is deliberately **not** given the deleted class's name: `CacheGrailsPlugin` derives `CacheAutoConfiguration`, and pinning the old `GrailsCacheAutoConfiguration` with `@GrailsBeans(autoConfigurationName = ...)` would have baked in a naming inconsistency the rest of the framework does not share — `UrlMappingsAutoConfiguration`, `Sitemesh3AutoConfiguration`, `MailAutoConfiguration`, `I18nAutoConfiguration` and `ControllersAutoConfiguration` all already follow the `*GrailsPlugin` -> `*AutoConfiguration` convention, and the redundant `Grails` prefix is the outlier. That attribute is for a name that genuinely cannot move, not for preserving legacy naming. Imports and comments are trimmed here; each linked filename is the verbatim, commit-pinned source.
Before, [`GrailsCacheAutoConfiguration.groovy`](https://github.com/codeconsole/grails-core/blob/100b9dbf77d65a32cef2f1698113052fa9f59ac7/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCacheAutoConfiguration.groovy#L45-L69) (since deleted):
```groovy
@AutoConfiguration
@ConditionalOnBooleanProperty(name = 'grails.cache.enabled', matchIfMissing = true)
@ConditionalOnBean(CachePluginConfiguration)
@CompileStatic
class GrailsCacheAutoConfiguration {
@Value('${grails.cache.cacheManager:}')
String cacheManagerType
@Bean
@ConditionalOnMissingBean(name = 'customCacheKeyGenerator')
CustomCacheKeyGenerator customCacheKeyGenerator() {
new CustomCacheKeyGenerator()
}
@Bean
@ConditionalOnMissingBean(name = 'grailsCacheManager')
GrailsCacheManager grailsCacheManager(CachePluginConfiguration grailsCacheConfiguration) {
if (cacheManagerType == 'GrailsConcurrentLinkedMapCacheManager') {
return new GrailsConcurrentLinkedMapCacheManager(configuration: grailsCacheConfiguration)
}
new GrailsConcurrentMapCacheManager(configuration: grailsCacheConfiguration)
}
}
```
After — [`CacheGrailsPlugin.groovy`](https://github.com/codeconsole/grails-core/blob/311fb9a959e646469432ba8983ee02319fffbd6c/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy#L50-L87)'s class declaration and `beans` block (the plugin's metadata properties between them are elided below, unchanged by the conversion; `beanRegistrar()` and `doWithApplicationContext()` further down the file are pre-existing plugin logic, untouched):
```groovy
@Slf4j
@CompileStatic
@GrailsBeans
@AutoConfiguration
@ConditionalOnBooleanProperty(name = 'grails.cache.enabled', matchIfMissing = true)
@ConditionalOnBean(CachePluginConfiguration)
class CacheGrailsPlugin extends Plugin {
// ... pre-existing plugin metadata properties and isCachingEnabled(), unchanged ...
def beans = {
field('cacheManagerType', String).value('grails.cache.cacheManager', '')
bean('customCacheKeyGenerator', CustomCacheKeyGenerator).conditionalOnMissingBeanName() {
new CustomCacheKeyGenerator()
}
bean('grailsCacheManager', GrailsCacheManager).conditionalOnMissingBeanName() { CachePluginConfiguration grailsCacheConfiguration ->
if (cacheManagerType == 'GrailsConcurrentLinkedMapCacheManager') {
return new GrailsConcurrentLinkedMapCacheManager(configuration: grailsCacheConfiguration)
}
new GrailsConcurrentMapCacheManager(configuration: grailsCacheConfiguration)
}
}
```
This conversion sits next to a `beanRegistrar()` that the two auto-configured beans are gated on: `@ConditionalOnBean(CachePluginConfiguration)` refers to the `grailsCacheConfiguration` definition the registrar contributes, and the registrar runs before auto-configuration conditions are evaluated, so the pair backs off entirely when the plugin is inactive — the jar on the classpath but the plugin excluded. The deleted class's design documentation now lives on the plugin, next to the registrar it describes. `@AutoConfiguration`, `@ConditionalOnBooleanProperty` and `@ConditionalOnBean` all move onto the sibling at compile time, and `@CompileStatic` is copied onto it so the generated configuration keeps the deleted class's static compilation.
The rename is contained: the only references were the module's own tests, so `GrailsCacheAutoConfigurationSpec` becomes `CacheAutoConfigurationSpec` and `CacheGrailsPluginSpec`'s description is updated. It remains a public FQCN change for anyone excluding the auto-configuration through `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude`, which a major release is the right place to take. The full `grails-cache` suite passes unmodified against the generated class, including `CacheAutoConfigurationSpec`'s direct `context.register(CacheAutoConfiguration)`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5099320501
## ✅ All tests passed ✅
🏷️ Commit: 29305023f40e8c6ed1f2aba24c54ddc704c5366c
▶️ Tests: 61304 executed
⚪️ Checks: 61/61 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5038350236
## ✅ All tests passed ✅
🏷️ Commit: 4cf0a7ab11f7068fbb624c2ba7079edec0beaa2b
▶️ Tests: 56474 executed
⚪️ Checks: 59/59 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5065908211
Thanks @matrei, all 3 points addressed:
- 48d352fadf: a bean name can now be declared by multiple `bean(...)` statements as long as every declaration has its own discriminating condition (e.g. `.annotate(ConditionalOnProperty, ...)`). Unconditioned duplicates are still a compile error. Your `UrlMappingsAutoConfiguration` conversion is now in the branch (5e9e162e99), see the Before/After comment above.
- 19a502c420: argument order flipped to name first: `bean('grailsUrlConverter', UrlConverter)`, `field('cacheUrls', Boolean)`, `method('fixedLocale', Locale)`. Type-only forms unchanged; the old order produces a compile error pointing at the new one.
- 855a28347d: `@GrailsBeans` works on any configuration source class, including the `Application` class (no imports-file entry needed there). Docs added to "Grails and Spring → Configuring Additional Beans" so they are no longer plugin-only.
Also, single-argument `.value(...)` now auto-wraps a bare key: `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` (32ead2bbc4). Strings containing `${...}`/`#{...}` still pass through verbatim.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3679574614
##########
grails-core/build.gradle:
##########
@@ -51,6 +51,8 @@ dependencies {
api 'jakarta.persistence:jakarta.persistence-api'
api 'jakarta.annotation:jakarta.annotation-api'
+ api project(':grails-beans-dsl')
Review Comment:
Agreed, and it stays. It now carries a comment recording the reasoning you set out here — that `compileBeansDsl` loads the transform reflectively and returns silently when it is absent, so this `api` is what makes the implicit `def beans = { }` convention reach a third-party plugin author (`138d014236`).
The other seven are removed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5082399009
## ✅ All tests passed ✅
🏷️ Commit: 5c71d9e88ceae522071f724681b5de2baafdb43a
▶️ Tests: 46898 executed
⚪️ Checks: 61/61 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5041536687
## ✅ All tests passed ✅
🏷️ Commit: 4dea95c0486094411b5f92092c5cd32a7b6ed34d
▶️ Tests: 56783 executed
⚪️ Checks: 59/59 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "matrei (via GitHub)" <gi...@apache.org>.
matrei commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5060209771
Hey @codeconsole, this looks cool!
I tried to get a feel for the DSL by converting the `UrlMappingsAutoConfiguration` and got the following error:
`"grailsUrlConverter" is already used as the Spring bean name of another bean(...)`
(adding `.primary()` did not help)
```groovy
bean(UrlConverter, 'grailsUrlConverter')
.conditionalOnMissingBeanName()
.annotate(ConditionalOnProperty, name: 'grails.web.url.converter', havingValue: 'camelCase', matchIfMissing: true) {
new CamelCaseUrlConverter()
}
bean(UrlConverter, 'grailsUrlConverter')
.conditionalOnMissingBeanName()
.annotate(ConditionalOnProperty, name: 'grails.web.url.converter', havingValue: 'hyphenated') {
new HyphenatedUrlConverter()
}
```
I think I would find it more intuitive/readable by switching the type/name parameter order:
```groovy
field('cacheUrls', Boolean).value('grails.web.linkGenerator.useCache')
field('serverURL', String).value('grails.serverURL')
method('fixedLocale', Locale) {
Locale.default
}
bean('grailsUrlConverter', UrlConverter) {
new MyUrlConverter()
}
```
You have put the documentation in the "Plugins" section, but wouldn't it be applicable to applications as well?
Would it for example be possible to put `@GrailsBeans` on the `Application` class to define the beans?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3705736464
##########
grails-doc/src/en/guide/conf/applicationClass/applicationLifeCycle.adoc:
##########
@@ -34,3 +34,5 @@ class Application extends GrailsAutoConfiguration {
...
}
----
+
+The `Application` class can also define its beans at compile time instead, by annotating it with `@GrailsBeans` — see link:spring.html#springdslAdditional[Configuring Additional Beans].
Review Comment:
Correct, it isn't — and this line contradicted the plugin and Spring chapters, which both already documented the annotation as implicit here. Reworded, and added a test for the Application path, which had none.
##########
grails-domain-class/src/main/groovy/org/grails/plugins/domain/DomainClassGrailsPlugin.groovy:
##########
@@ -45,15 +55,26 @@ class DomainClassGrailsPlugin extends Plugin {
def dependsOn = [i18n: version]
def loadAfter = ['controllers', 'dataSource']
- @Override
- BeanRegistrar beanRegistrar() {
- return { BeanRegistry registry, Environment environment ->
- // Set default for auto-timestamp annotation caching based on environment if not explicitly configured
- Config config = grailsApplication.config
- if (!config.containsProperty(DatastoreSettings.SETTING_AUTO_TIMESTAMP_CACHE_ANNOTATIONS)) {
- // Not configured - disable caching in development mode to support class reloading
- config.put(DatastoreSettings.SETTING_AUTO_TIMESTAMP_CACHE_ANNOTATIONS,
- !grails.util.Environment.isDevelopmentMode())
+ // The deleted class held grailsApplication and messageSources as fields populated by an
+ // @Autowired constructor. The generated sibling always has a no-arg constructor, so both are
+ // taken as bean method parameters instead - resolved identically by Spring, and only when the
+ // bean that needs them is created rather than when the configuration class is instantiated.
Review Comment:
Removed — it described the constructor of the class this PR deletes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3679572495
##########
grails-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:
##########
@@ -1 +1 @@
-org.grails.plugins.core.CoreAutoConfiguration
\ No newline at end of file
+org.grails.plugins.CoreAutoConfiguration
Review Comment:
Documented rather than made configurable, in `0067d15e23`. The three FQCN changes the guide was missing now get the same treatment as line 1582 — `CoreAutoConfiguration`'s package move, `GrailsCacheAutoConfiguration` → `CacheAutoConfiguration`, and `DataBindingConfiguration` → `DataBindingAutoConfiguration` — including your point that Spring Boot only reports an invalid exclude for a class still on the classpath, so a stale entry is ignored in silence and the beans it was meant to suppress register anyway.
Teaching `autoConfigurationName` to take a fully-qualified name was the deliberate non-choice: these classes should carry their convention name, and an escape hatch that lets one keep a package it no longer lives beside would undercut that.
##########
grails-doc/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc:
##########
@@ -119,6 +119,143 @@ class I18nGrailsPlugin extends Plugin {
A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.
+==== Compiling Bean Definitions into a Spring Boot AutoConfiguration
+
+
+`beanRegistrar()` and `doWithSpring` register beans at a single, fixed point in startup: before Spring Boot processes any `{springbootapi}org/springframework/boot/autoconfigure/AutoConfiguration.html[AutoConfiguration]`. That is enough for a bean to win against a Boot default guarded by `@ConditionalOnMissingBean`, but it cannot express ordering *relative to a specific* auto-configuration — running before `WebMvcAutoConfiguration` but after `MessageSourceAutoConfiguration`, say, regardless of where those two land in Boot's overall sort. Only a real `AutoConfiguration` class can declare that ordering, via `@AutoConfiguration(before = ..., after = ...)`.
+
+The link:{api}grails/compiler/beans/GrailsBeans.html[GrailsBeans] annotation lets you author bean definitions with DSL syntax similar to the classic Beans DSL, while compiling them at build time into genuine `@Bean` factory methods on a plain `AutoConfiguration` class — no closures, and nothing DSL-specific, survive into the compiled bytecode. Add `org.apache.grails:grails-beans-dsl` as a dependency and annotate a class whose `beans` property is a closure of `bean(["name", ] Type) { ... }` statements:
+
+[source,groovy]
+----
+import grails.compiler.beans.GrailsBeans
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration
+import org.springframework.context.MessageSource
+import org.springframework.context.support.ReloadableResourceBundleMessageSource
+import org.springframework.web.servlet.i18n.CookieLocaleResolver
+import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
+
+@GrailsBeans
+@AutoConfiguration(before = [MessageSourceAutoConfiguration, WebMvcAutoConfiguration])
+class I18nBeans {
+
+ def beans = {
+ bean('messageSource', ReloadableResourceBundleMessageSource) {
+ new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
+ }
+
+ bean('localeResolver', CookieLocaleResolver).conditionalOnMissingBean(CookieLocaleResolver) {
+ new CookieLocaleResolver('locale')
+ }
+
+ bean('localeChangeInterceptor', LocaleChangeInterceptor) { MessageSource messageSource ->
+ new LocaleChangeInterceptor(paramName: 'lang')
+ }
+ }
+}
+----
+
+Each `bean(["name", ] Type)` statement compiles to a public method returning the declared type and annotated `@Bean("name")`. The generated method's name is an implementation detail — Spring resolves the bean by its `@Bean("name")` value, never by the method name. It matches the bean name when that is a valid Java identifier not already taken by an existing member (declared, inherited, or defined elsewhere in the DSL — a bean named `toString` will not override `Object.toString()`); otherwise a synthesized `<type>$N` name (`service$0`, `service$1`, ...) is used instead, so any legal, non-blank Spring bean name compiles:
+
+* The bean name defaults to the decapitalized simple class name when omitted.
+* The same bean name may be declared by more than one `bean(...)` statement — the standard Spring Boot pattern for mutually exclusive variants of one bean, such as the framework's own `grailsUrlConverter` selected by `@ConditionalOnProperty` — provided every declaration with the name carries its own discriminating condition (such as `.annotate(ConditionalOnProperty, ...)`), so that at most one of them registers at runtime. Duplicating a bean name without that is a compile-time error, since Spring would keep the first definition and silently skip the rest.
+* Chaining `.conditionalOnMissingBean(...)` adds a `@ConditionalOnMissingBean` annotation to the generated method, matching Spring Boot's usual back-off semantics. It takes positional types (`.conditionalOnMissingBean(Greeter)`), the annotation's own named attributes (`.conditionalOnMissingBean(name: 'localeResolver', search: SearchStrategy.CURRENT)`), or both. With no arguments at all it compiles to the bare annotation, letting Spring Boot infer the back-off type from the method's return type — the recommended form when a bean simply backs off its own type, since `bean(AvailableLocaleResolver).conditionalOnMissingBean()` already says everything `.conditionalOnMissingBean(AvailableLocaleResolver)` would repeat.
+* Chaining `.conditionalOnMissingBeanName(...)` is the name-based counterpart: "register this bean unless a bean with *this bean's name* already exists". The condition's `name` member is set from the bean's own (explicit or convention-derived) name, so `bean(MessageSource).conditionalOnMissingBeanName(search: SearchStrategy.CURRENT) { ... }` states `messageSource` once and it feeds both `@Bean` and the condition — the two strings the explicit form has to keep in sync cannot diverge. It accepts the annotation's other attributes (`search:`, `ignored:`, ...) but rejects `name:` and types, which would contradict its purpose; use `.conditionalOnMissingBean(...)` for those.
+* Chaining `.primary()`, `.lazy()`, and/or `.scope("name")` adds `@Primary`, `@Lazy`, and `@Scope("name")` respectively.
+* Chaining `.staticMethod()` makes the generated factory method `static` — Spring's recommended shape for `BeanFactoryPostProcessor` and `BeanPostProcessor` beans, which must be creatable without instantiating their declaring configuration class. A static bean's closure cannot reference `field(...)` or `method(...)` members, since those are instance members; under `@CompileStatic` that mistake is a compile error.
+* Chaining `.annotate(AnnotationType[, attr: value, ...])` attaches any other single-valued annotation directly — any `@Conditional*` (built-in or a custom `Condition`), `@Order`, `@DependsOn`, or anything else a hand-written `@Bean` method could carry. It's repeatable, so several different annotations can be chained onto the same bean: `bean('special', Special).annotate(Order, value: 1).annotate(ConditionalOnProperty, prefix: 'myapp', name: 'enabled', havingValue: 'true') { ... }`.
+* Any combination of the above can be chained together, in any order — for example `bean('slowGreeter', SlowGreeter).lazy().scope('prototype') { ... }`.
+* Typed closure parameters (`{ MessageSource messageSource -> ... }`) become the generated method's parameters, so other beans are injected the same way a hand-written `@Bean` method would declare them — and a parameter-level annotation such as `{ @Qualifier('special') Greeter g -> ... }` carries straight through too, since the closure's own parameters become the generated method's parameters directly.
+
+Two more statement kinds can appear inside `beans { }` alongside `bean(...)`, for state and logic shared across bean methods — the same role a hand-written `@Configuration` class's own fields and private methods play:
+
+* `field(["name", ] Type)`, optionally chained with `.value(...)` and/or (repeatably) `.annotate(AnnotationType[, attr: value, ...])`, declares a private field on the generated class. The usual case is injected configuration, and `.value(...)` covers it directly: `field('encoding', String).value('grails.gsp.view.encoding', 'UTF-8')` compiles to `@Value("${grails.gsp.view.encoding:UTF-8}")`. The two-argument form takes a config key and default — and because the DSL builds the placeholder itself, the key may be a bare constant reference (`.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')`), the one shape a directly-written annotation value can't accept. The one-argument form takes a bare config key with no default — `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` — while a string already containing a `${...}` placeholder or a `#{...}` SpEL expression passes through verbatim: `.value('#{T(java.lang.Runtime).getRuntime().availab
leProcessors()}')`.
Review Comment:
Fixed in `0067d15e23`. The key does not exist; the doc and the spec fixture both now use `grails.views.gsp.encoding`, which is what `Settings.GSP_VIEW_ENCODING` holds.
##########
grails-doc/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc:
##########
@@ -119,6 +119,143 @@ class I18nGrailsPlugin extends Plugin {
A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.
+==== Compiling Bean Definitions into a Spring Boot AutoConfiguration
+
+
+`beanRegistrar()` and `doWithSpring` register beans at a single, fixed point in startup: before Spring Boot processes any `{springbootapi}org/springframework/boot/autoconfigure/AutoConfiguration.html[AutoConfiguration]`. That is enough for a bean to win against a Boot default guarded by `@ConditionalOnMissingBean`, but it cannot express ordering *relative to a specific* auto-configuration — running before `WebMvcAutoConfiguration` but after `MessageSourceAutoConfiguration`, say, regardless of where those two land in Boot's overall sort. Only a real `AutoConfiguration` class can declare that ordering, via `@AutoConfiguration(before = ..., after = ...)`.
+
+The link:{api}grails/compiler/beans/GrailsBeans.html[GrailsBeans] annotation lets you author bean definitions with DSL syntax similar to the classic Beans DSL, while compiling them at build time into genuine `@Bean` factory methods on a plain `AutoConfiguration` class — no closures, and nothing DSL-specific, survive into the compiled bytecode. Add `org.apache.grails:grails-beans-dsl` as a dependency and annotate a class whose `beans` property is a closure of `bean(["name", ] Type) { ... }` statements:
+
+[source,groovy]
+----
+import grails.compiler.beans.GrailsBeans
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration
+import org.springframework.context.MessageSource
+import org.springframework.context.support.ReloadableResourceBundleMessageSource
+import org.springframework.web.servlet.i18n.CookieLocaleResolver
+import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
+
+@GrailsBeans
+@AutoConfiguration(before = [MessageSourceAutoConfiguration, WebMvcAutoConfiguration])
+class I18nBeans {
+
+ def beans = {
+ bean('messageSource', ReloadableResourceBundleMessageSource) {
+ new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
+ }
+
+ bean('localeResolver', CookieLocaleResolver).conditionalOnMissingBean(CookieLocaleResolver) {
+ new CookieLocaleResolver('locale')
+ }
+
+ bean('localeChangeInterceptor', LocaleChangeInterceptor) { MessageSource messageSource ->
+ new LocaleChangeInterceptor(paramName: 'lang')
+ }
+ }
+}
+----
+
+Each `bean(["name", ] Type)` statement compiles to a public method returning the declared type and annotated `@Bean("name")`. The generated method's name is an implementation detail — Spring resolves the bean by its `@Bean("name")` value, never by the method name. It matches the bean name when that is a valid Java identifier not already taken by an existing member (declared, inherited, or defined elsewhere in the DSL — a bean named `toString` will not override `Object.toString()`); otherwise a synthesized `<type>$N` name (`service$0`, `service$1`, ...) is used instead, so any legal, non-blank Spring bean name compiles:
+
+* The bean name defaults to the decapitalized simple class name when omitted.
+* The same bean name may be declared by more than one `bean(...)` statement — the standard Spring Boot pattern for mutually exclusive variants of one bean, such as the framework's own `grailsUrlConverter` selected by `@ConditionalOnProperty` — provided every declaration with the name carries its own discriminating condition (such as `.annotate(ConditionalOnProperty, ...)`), so that at most one of them registers at runtime. Duplicating a bean name without that is a compile-time error, since Spring would keep the first definition and silently skip the rest.
+* Chaining `.conditionalOnMissingBean(...)` adds a `@ConditionalOnMissingBean` annotation to the generated method, matching Spring Boot's usual back-off semantics. It takes positional types (`.conditionalOnMissingBean(Greeter)`), the annotation's own named attributes (`.conditionalOnMissingBean(name: 'localeResolver', search: SearchStrategy.CURRENT)`), or both. With no arguments at all it compiles to the bare annotation, letting Spring Boot infer the back-off type from the method's return type — the recommended form when a bean simply backs off its own type, since `bean(AvailableLocaleResolver).conditionalOnMissingBean()` already says everything `.conditionalOnMissingBean(AvailableLocaleResolver)` would repeat.
+* Chaining `.conditionalOnMissingBeanName(...)` is the name-based counterpart: "register this bean unless a bean with *this bean's name* already exists". The condition's `name` member is set from the bean's own (explicit or convention-derived) name, so `bean(MessageSource).conditionalOnMissingBeanName(search: SearchStrategy.CURRENT) { ... }` states `messageSource` once and it feeds both `@Bean` and the condition — the two strings the explicit form has to keep in sync cannot diverge. It accepts the annotation's other attributes (`search:`, `ignored:`, ...) but rejects `name:` and types, which would contradict its purpose; use `.conditionalOnMissingBean(...)` for those.
+* Chaining `.primary()`, `.lazy()`, and/or `.scope("name")` adds `@Primary`, `@Lazy`, and `@Scope("name")` respectively.
+* Chaining `.staticMethod()` makes the generated factory method `static` — Spring's recommended shape for `BeanFactoryPostProcessor` and `BeanPostProcessor` beans, which must be creatable without instantiating their declaring configuration class. A static bean's closure cannot reference `field(...)` or `method(...)` members, since those are instance members; under `@CompileStatic` that mistake is a compile error.
+* Chaining `.annotate(AnnotationType[, attr: value, ...])` attaches any other single-valued annotation directly — any `@Conditional*` (built-in or a custom `Condition`), `@Order`, `@DependsOn`, or anything else a hand-written `@Bean` method could carry. It's repeatable, so several different annotations can be chained onto the same bean: `bean('special', Special).annotate(Order, value: 1).annotate(ConditionalOnProperty, prefix: 'myapp', name: 'enabled', havingValue: 'true') { ... }`.
+* Any combination of the above can be chained together, in any order — for example `bean('slowGreeter', SlowGreeter).lazy().scope('prototype') { ... }`.
+* Typed closure parameters (`{ MessageSource messageSource -> ... }`) become the generated method's parameters, so other beans are injected the same way a hand-written `@Bean` method would declare them — and a parameter-level annotation such as `{ @Qualifier('special') Greeter g -> ... }` carries straight through too, since the closure's own parameters become the generated method's parameters directly.
+
+Two more statement kinds can appear inside `beans { }` alongside `bean(...)`, for state and logic shared across bean methods — the same role a hand-written `@Configuration` class's own fields and private methods play:
+
+* `field(["name", ] Type)`, optionally chained with `.value(...)` and/or (repeatably) `.annotate(AnnotationType[, attr: value, ...])`, declares a private field on the generated class. The usual case is injected configuration, and `.value(...)` covers it directly: `field('encoding', String).value('grails.gsp.view.encoding', 'UTF-8')` compiles to `@Value("${grails.gsp.view.encoding:UTF-8}")`. The two-argument form takes a config key and default — and because the DSL builds the placeholder itself, the key may be a bare constant reference (`.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')`), the one shape a directly-written annotation value can't accept. The one-argument form takes a bare config key with no default — `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` — while a string already containing a `${...}` placeholder or a `#{...}` SpEL expression passes through verbatim: `.value('#{T(java.lang.Runtime).getRuntime().availab
leProcessors()}')`.
+* `method(["name", ] Type) { ... }`, chainable with `.annotate(...)` only (`.value(...)` is field-specific), declares a private helper method the same way `bean(...)` declares a public one — typed closure parameters become method parameters, and the closure body becomes the method body.
+
+Both are ordinary private members of the generated class, so a `bean(...)` closure reads a `field(...)` or calls a `method(...)` exactly like a hand-written `@Bean` method would reference a sibling field or method on its own class:
+
+[source,groovy]
+----
+field('suffix', String).value('myapp.greeting-suffix', '!')
+
+method('buildGreeting', String) { String name ->
+ "Hello, ${name}${suffix}"
+}
+
+bean('greeting', Greeting) {
+ new Greeting(buildGreeting('World'))
+}
+----
+
+Because the result is an ordinary `AutoConfiguration` class, it must be registered the same way any Spring Boot auto-configuration is: listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`. Modules built as part of this project can apply the `org.apache.grails.buildsrc.autoconfiguration-imports` Gradle convention plugin to generate that file automatically, by scanning the module's own compiled classes for `@AutoConfiguration` at build time. Projects outside this build register the class the same way any hand-written `AutoConfiguration` is registered — by listing it in that file directly.
+
+NOTE: `@GrailsBeans` does not require extending `Plugin` at all — it produces a plain Spring Boot `AutoConfiguration`, so it can be used by any Spring Boot module, not just a Grails plugin descriptor. Applications can use it too, including directly on the `Application` class — where no imports-file registration is needed, since Spring Boot processes the application class itself — see link:spring.html#springdslAdditional[Configuring Additional Beans]. Within a plugin, reach for it specifically when a bean's registration needs to be ordered against a particular other auto-configuration; otherwise `beanRegistrar()` remains the recommended way to register beans from a `Plugin`.
+
+The DSL still covers a narrower surface than `doWithSpring(BeanBuilder)`:
+
+* Each top-level statement inside `beans { }` must be exactly `bean(...)`, `field(...)`, or `method(...)`, with their respective chaining — an `if`, a `for` loop, or any other imperative Groovy directly inside `beans { }` is a compile-time error, not a runtime one. Note that this is about the DSL's own top-level statements, not the bodies of `bean(...)`/`method(...)` closures themselves, which accept arbitrary Groovy — and `field(...)`/`method(...)` already cover the common reasons to want shared state or logic in the first place.
+* `.annotate(...)` attribute values must be simple compile-time constants (strings, numbers, booleans, class literals, enum constants, or arrays of these) — an annotation attribute that itself takes a nested annotation as a value isn't supported.
Review Comment:
Rewritten in `0067d15e23` along the lines your table establishes: a bare constant reference does fold, and the two shapes that do not are a `static final` on a Groovy *class* (a property whose getter `@CompileStatic` rewrites the reference into) and a concatenation of constants.
The consequence you predicted is fixed too, in `af64be699c`: `UrlMappingsGrailsPlugin` is back on `Settings.WEB_URL_CONVERTER` and `Settings.SETTING_CORS_FILTER`, and the comment justifying the literals is gone.
##########
grails-doc/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc:
##########
@@ -119,6 +119,143 @@ class I18nGrailsPlugin extends Plugin {
A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.
+==== Compiling Bean Definitions into a Spring Boot AutoConfiguration
+
+
+`beanRegistrar()` and `doWithSpring` register beans at a single, fixed point in startup: before Spring Boot processes any `{springbootapi}org/springframework/boot/autoconfigure/AutoConfiguration.html[AutoConfiguration]`. That is enough for a bean to win against a Boot default guarded by `@ConditionalOnMissingBean`, but it cannot express ordering *relative to a specific* auto-configuration — running before `WebMvcAutoConfiguration` but after `MessageSourceAutoConfiguration`, say, regardless of where those two land in Boot's overall sort. Only a real `AutoConfiguration` class can declare that ordering, via `@AutoConfiguration(before = ..., after = ...)`.
+
+The link:{api}grails/compiler/beans/GrailsBeans.html[GrailsBeans] annotation lets you author bean definitions with DSL syntax similar to the classic Beans DSL, while compiling them at build time into genuine `@Bean` factory methods on a plain `AutoConfiguration` class — no closures, and nothing DSL-specific, survive into the compiled bytecode. Add `org.apache.grails:grails-beans-dsl` as a dependency and annotate a class whose `beans` property is a closure of `bean(["name", ] Type) { ... }` statements:
+
+[source,groovy]
+----
+import grails.compiler.beans.GrailsBeans
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration
+import org.springframework.context.MessageSource
+import org.springframework.context.support.ReloadableResourceBundleMessageSource
+import org.springframework.web.servlet.i18n.CookieLocaleResolver
+import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
+
+@GrailsBeans
+@AutoConfiguration(before = [MessageSourceAutoConfiguration, WebMvcAutoConfiguration])
+class I18nBeans {
+
+ def beans = {
+ bean('messageSource', ReloadableResourceBundleMessageSource) {
+ new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
+ }
+
+ bean('localeResolver', CookieLocaleResolver).conditionalOnMissingBean(CookieLocaleResolver) {
+ new CookieLocaleResolver('locale')
+ }
+
+ bean('localeChangeInterceptor', LocaleChangeInterceptor) { MessageSource messageSource ->
+ new LocaleChangeInterceptor(paramName: 'lang')
+ }
+ }
+}
+----
+
+Each `bean(["name", ] Type)` statement compiles to a public method returning the declared type and annotated `@Bean("name")`. The generated method's name is an implementation detail — Spring resolves the bean by its `@Bean("name")` value, never by the method name. It matches the bean name when that is a valid Java identifier not already taken by an existing member (declared, inherited, or defined elsewhere in the DSL — a bean named `toString` will not override `Object.toString()`); otherwise a synthesized `<type>$N` name (`service$0`, `service$1`, ...) is used instead, so any legal, non-blank Spring bean name compiles:
+
+* The bean name defaults to the decapitalized simple class name when omitted.
+* The same bean name may be declared by more than one `bean(...)` statement — the standard Spring Boot pattern for mutually exclusive variants of one bean, such as the framework's own `grailsUrlConverter` selected by `@ConditionalOnProperty` — provided every declaration with the name carries its own discriminating condition (such as `.annotate(ConditionalOnProperty, ...)`), so that at most one of them registers at runtime. Duplicating a bean name without that is a compile-time error, since Spring would keep the first definition and silently skip the rest.
+* Chaining `.conditionalOnMissingBean(...)` adds a `@ConditionalOnMissingBean` annotation to the generated method, matching Spring Boot's usual back-off semantics. It takes positional types (`.conditionalOnMissingBean(Greeter)`), the annotation's own named attributes (`.conditionalOnMissingBean(name: 'localeResolver', search: SearchStrategy.CURRENT)`), or both. With no arguments at all it compiles to the bare annotation, letting Spring Boot infer the back-off type from the method's return type — the recommended form when a bean simply backs off its own type, since `bean(AvailableLocaleResolver).conditionalOnMissingBean()` already says everything `.conditionalOnMissingBean(AvailableLocaleResolver)` would repeat.
+* Chaining `.conditionalOnMissingBeanName(...)` is the name-based counterpart: "register this bean unless a bean with *this bean's name* already exists". The condition's `name` member is set from the bean's own (explicit or convention-derived) name, so `bean(MessageSource).conditionalOnMissingBeanName(search: SearchStrategy.CURRENT) { ... }` states `messageSource` once and it feeds both `@Bean` and the condition — the two strings the explicit form has to keep in sync cannot diverge. It accepts the annotation's other attributes (`search:`, `ignored:`, ...) but rejects `name:` and types, which would contradict its purpose; use `.conditionalOnMissingBean(...)` for those.
+* Chaining `.primary()`, `.lazy()`, and/or `.scope("name")` adds `@Primary`, `@Lazy`, and `@Scope("name")` respectively.
+* Chaining `.staticMethod()` makes the generated factory method `static` — Spring's recommended shape for `BeanFactoryPostProcessor` and `BeanPostProcessor` beans, which must be creatable without instantiating their declaring configuration class. A static bean's closure cannot reference `field(...)` or `method(...)` members, since those are instance members; under `@CompileStatic` that mistake is a compile error.
+* Chaining `.annotate(AnnotationType[, attr: value, ...])` attaches any other single-valued annotation directly — any `@Conditional*` (built-in or a custom `Condition`), `@Order`, `@DependsOn`, or anything else a hand-written `@Bean` method could carry. It's repeatable, so several different annotations can be chained onto the same bean: `bean('special', Special).annotate(Order, value: 1).annotate(ConditionalOnProperty, prefix: 'myapp', name: 'enabled', havingValue: 'true') { ... }`.
+* Any combination of the above can be chained together, in any order — for example `bean('slowGreeter', SlowGreeter).lazy().scope('prototype') { ... }`.
+* Typed closure parameters (`{ MessageSource messageSource -> ... }`) become the generated method's parameters, so other beans are injected the same way a hand-written `@Bean` method would declare them — and a parameter-level annotation such as `{ @Qualifier('special') Greeter g -> ... }` carries straight through too, since the closure's own parameters become the generated method's parameters directly.
+
+Two more statement kinds can appear inside `beans { }` alongside `bean(...)`, for state and logic shared across bean methods — the same role a hand-written `@Configuration` class's own fields and private methods play:
+
+* `field(["name", ] Type)`, optionally chained with `.value(...)` and/or (repeatably) `.annotate(AnnotationType[, attr: value, ...])`, declares a private field on the generated class. The usual case is injected configuration, and `.value(...)` covers it directly: `field('encoding', String).value('grails.gsp.view.encoding', 'UTF-8')` compiles to `@Value("${grails.gsp.view.encoding:UTF-8}")`. The two-argument form takes a config key and default — and because the DSL builds the placeholder itself, the key may be a bare constant reference (`.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')`), the one shape a directly-written annotation value can't accept. The one-argument form takes a bare config key with no default — `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` — while a string already containing a `${...}` placeholder or a `#{...}` SpEL expression passes through verbatim: `.value('#{T(java.lang.Runtime).getRuntime().availab
leProcessors()}')`.
+* `method(["name", ] Type) { ... }`, chainable with `.annotate(...)` only (`.value(...)` is field-specific), declares a private helper method the same way `bean(...)` declares a public one — typed closure parameters become method parameters, and the closure body becomes the method body.
+
+Both are ordinary private members of the generated class, so a `bean(...)` closure reads a `field(...)` or calls a `method(...)` exactly like a hand-written `@Bean` method would reference a sibling field or method on its own class:
+
+[source,groovy]
+----
+field('suffix', String).value('myapp.greeting-suffix', '!')
+
+method('buildGreeting', String) { String name ->
+ "Hello, ${name}${suffix}"
+}
+
+bean('greeting', Greeting) {
+ new Greeting(buildGreeting('World'))
+}
+----
+
+Because the result is an ordinary `AutoConfiguration` class, it must be registered the same way any Spring Boot auto-configuration is: listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`. Modules built as part of this project can apply the `org.apache.grails.buildsrc.autoconfiguration-imports` Gradle convention plugin to generate that file automatically, by scanning the module's own compiled classes for `@AutoConfiguration` at build time. Projects outside this build register the class the same way any hand-written `AutoConfiguration` is registered — by listing it in that file directly.
+
+NOTE: `@GrailsBeans` does not require extending `Plugin` at all — it produces a plain Spring Boot `AutoConfiguration`, so it can be used by any Spring Boot module, not just a Grails plugin descriptor. Applications can use it too, including directly on the `Application` class — where no imports-file registration is needed, since Spring Boot processes the application class itself — see link:spring.html#springdslAdditional[Configuring Additional Beans]. Within a plugin, reach for it specifically when a bean's registration needs to be ordered against a particular other auto-configuration; otherwise `beanRegistrar()` remains the recommended way to register beans from a `Plugin`.
+
+The DSL still covers a narrower surface than `doWithSpring(BeanBuilder)`:
+
+* Each top-level statement inside `beans { }` must be exactly `bean(...)`, `field(...)`, or `method(...)`, with their respective chaining — an `if`, a `for` loop, or any other imperative Groovy directly inside `beans { }` is a compile-time error, not a runtime one. Note that this is about the DSL's own top-level statements, not the bodies of `bean(...)`/`method(...)` closures themselves, which accept arbitrary Groovy — and `field(...)`/`method(...)` already cover the common reasons to want shared state or logic in the first place.
+* `.annotate(...)` attribute values must be simple compile-time constants (strings, numbers, booleans, class literals, enum constants, or arrays of these) — an annotation attribute that itself takes a nested annotation as a value isn't supported.
+* Dependencies on other beans are expressed only through typed closure parameters (autowired by type), not by name — there is no `ref('beanName')` lookup.
Review Comment:
Added in `0067d15e23`, and the "arbitrary Groovy" bullet now points at it rather than encouraging the mistake.
Two tests: the `@CompileStatic` diagnostic for a body reading `config`, and the shape of the generated class that makes it so — extends `Object`, no `Plugin` in its hierarchy, only a no-arg constructor, no field that could hold one.
##########
grails-beans-dsl-plugin-example/src/main/groovy/beandsl/example/plugin/GreetingGrailsPlugin.groovy:
##########
@@ -0,0 +1,52 @@
+/*
+ * 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 beandsl.example.plugin
+
+import org.springframework.beans.factory.annotation.Value
+import org.springframework.boot.autoconfigure.AutoConfiguration
+
+import grails.compiler.beans.GrailsBeans
+import grails.plugins.Plugin
+
+/**
+ * Demonstrates {@code field(...)} and {@code method(...)} - the same shape real autoconfigurations
+ * like the built-in i18n plugin's need: injected configuration shared across beans, and a private
+ * helper factored out of a bean's construction logic. Both compile onto the generated
+ * {@code GreetingGrailsPluginAutoConfiguration} sibling as ordinary private members, exactly like
Review Comment:
Fixed in `af64be699c`. The suffix is replaced, so it is `GreetingAutoConfiguration`.
Your diagnosis of why nothing caught it was exactly right, so the Greeting spec now asserts the FQCN the way the Farewell one does, plus that the `field(...)` and `method(...)` members landed on the sibling rather than the plugin class.
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GenerateAutoConfigurationImportsTask.groovy:
##########
@@ -0,0 +1,133 @@
+/*
+ * 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.buildsrc
+
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.ConfigurableFileCollection
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.tasks.Classpath
+import org.gradle.api.tasks.IgnoreEmptyDirectories
+import org.gradle.api.tasks.InputFiles
+import org.gradle.api.tasks.OutputDirectory
+import org.gradle.api.tasks.PathSensitive
+import org.gradle.api.tasks.PathSensitivity
+import org.gradle.api.tasks.TaskAction
+
+/**
+ * Scans this project's own compiled main classes for {@code @AutoConfiguration} and writes
+ * {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the
+ * file never needs to be hand-maintained. Mirrors how {@code META-INF/grails-plugin.xml} is already
+ * generated from scanned {@code *GrailsPlugin} classes elsewhere in this build.
+ *
+ * <p>Classes are inspected via a scratch {@link URLClassLoader} over this project's own runtime
+ * classpath, isolated from the Gradle daemon's classpath (parent set to the platform loader) so a
+ * different Spring/Groovy version on the daemon's classpath cannot shadow the project's own.
+ */
+abstract class GenerateAutoConfigurationImportsTask extends DefaultTask {
+
+ static final String IMPORTS_RESOURCE_PATH =
+ 'META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports'
+
+ static final String AUTO_CONFIGURATION_ANNOTATION = 'org.springframework.boot.autoconfigure.AutoConfiguration'
+
+ @InputFiles
+ @IgnoreEmptyDirectories
+ @PathSensitive(PathSensitivity.RELATIVE)
+ abstract ConfigurableFileCollection getClassesDirs()
+
+ /**
+ * The classpath the scratch classloader resolves annotations/supertypes against. Deliberately
+ * built from the project's compile classpath (dependencies only) rather than its runtime
+ * classpath: the runtime classpath includes the source set's own output, which - once this
+ * task's generated directory is registered on that same output - would make this task depend
+ * on itself.
+ */
+ @Classpath
+ abstract ConfigurableFileCollection getScanClasspath()
+
+ @OutputDirectory
+ abstract DirectoryProperty getOutputDirectory()
+
+ @TaskAction
+ void generate() {
+ SortedSet<String> discovered = scan(classesDirs.files, scanClasspath.files) { String className, Throwable failure ->
+ logger.warn('generateAutoConfigurationImports: could not inspect {} - it will be excluded from ' +
+ 'the generated imports file even if it is genuinely annotated @AutoConfiguration. Cause: {}',
+ className, failure.toString())
+ }
+ File importsFile = outputDirectory.file(IMPORTS_RESOURCE_PATH).get().asFile
+ importsFile.parentFile.mkdirs()
+ importsFile.text = discovered.isEmpty() ? '' : discovered.join('\n') + '\n'
+ }
+
+ /**
+ * Package-private so it is directly unit-testable without running a real Gradle task.
+ *
+ * @param classesDirs directories of compiled {@code .class} files to inspect (a project's own
+ * output only - dependency jars on {@code classpathFiles} are never scanned for candidates)
+ * @param classpathFiles the classpath the scratch classloader resolves supertypes/annotations
+ * against; must include {@code classesDirs} plus every runtime dependency
+ * @param onUnresolvable invoked with (className, failure) for every candidate class that could
+ * not be loaded against {@code classpathFiles}. Defaults to a no-op so existing callers are
+ * unaffected; {@link #generate()} passes a callback that logs a build warning, since a class
+ * that fails to load here is silently excluded from the generated imports file - which, if it
+ * was genuinely a real {@code @AutoConfiguration}, means its beans would never be registered
+ * with no other signal that anything went wrong.
+ * @return the fully-qualified names of every top-level class annotated {@code @AutoConfiguration},
+ * sorted for a deterministic, diff-friendly output file
+ */
+ static SortedSet<String> scan(Set<File> classesDirs, Set<File> classpathFiles,
+ Closure<?> onUnresolvable = { String className, Throwable failure -> }) {
+ URL[] urls = classpathFiles.collect { it.toURI().toURL() } as URL[]
+ URLClassLoader scanLoader = new URLClassLoader(urls, ClassLoader.systemClassLoader.parent)
+ try {
+ Class<?> autoConfigurationAnnotation = Class.forName(AUTO_CONFIGURATION_ANNOTATION, false, scanLoader)
+ SortedSet<String> discovered = new TreeSet<>()
+ classesDirs.each { dir -> scanDirectory(dir, scanLoader, autoConfigurationAnnotation, discovered, onUnresolvable) }
+ discovered
+ }
+ finally {
+ scanLoader.close()
+ }
+ }
+
+ private static void scanDirectory(File dir, URLClassLoader scanLoader, Class<?> autoConfigurationAnnotation,
+ SortedSet<String> discovered, Closure<?> onUnresolvable) {
+ if (!dir.exists()) {
+ return
+ }
+ dir.eachFileRecurse(groovy.io.FileType.FILES) { file ->
+ if (!file.name.endsWith('.class') || file.name.contains('$')) {
+ return
+ }
+ String relative = dir.toPath().relativize(file.toPath()).toString()
+ String className = relative.replace(File.separator, '.') - '.class'
Review Comment:
Fixed in `62b74b9a3f`. The extension is dropped by length now. Test uses a `fixture/classloading` package — the exact mangling you described — and asserts both that the class is found and that the unresolvable-class callback does not fire.
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/AutoConfigurationImportsPlugin.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.buildsrc
+
+import groovy.transform.CompileStatic
+
+import org.gradle.api.Plugin
+import org.gradle.api.Project
+import org.gradle.api.file.Directory
+import org.gradle.api.plugins.JavaPluginExtension
+import org.gradle.api.provider.Provider
+import org.gradle.api.tasks.SourceSet
+import org.gradle.api.tasks.TaskProvider
+
+/**
+ * Convention plugin that wires {@link GenerateAutoConfigurationImportsTask} into the {@code main}
+ * source set's output, so a module authoring {@code @AutoConfiguration} classes never has to
+ * hand-maintain {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}.
+ *
+ * <p>The generated resources directory is registered via {@code sourceSets.main.output.dir(...)}
+ * rather than routed through {@code processResources}, so it lands on the compile/runtime/test
+ * classpath and in the final jar without depending on {@code Copy}-task ordering semantics.
+ */
+@CompileStatic
+class AutoConfigurationImportsPlugin implements Plugin<Project> {
+
+ static final String TASK_NAME = 'generateAutoConfigurationImports'
+ static final String GENERATED_RESOURCES_PATH = 'generated/resources/autoConfigurationImports'
+
+ @Override
+ void apply(Project project) {
+ project.pluginManager.apply('java-base')
+
+ SourceSet main = project.extensions.getByType(JavaPluginExtension).sourceSets.getByName('main')
+ Provider<Directory> generatedDir = project.layout.buildDirectory.dir(GENERATED_RESOURCES_PATH)
+
+ TaskProvider<GenerateAutoConfigurationImportsTask> task = project.tasks.register(
+ TASK_NAME, GenerateAutoConfigurationImportsTask) { GenerateAutoConfigurationImportsTask t ->
+ t.group = 'build'
+ t.description = 'Generates META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports ' +
+ 'by scanning compiled classes for @AutoConfiguration'
+ t.classesDirs.from(main.output.classesDirs)
+ t.scanClasspath.from(main.compileClasspath, main.output.classesDirs)
+ t.outputDirectory.set(generatedDir)
+ }
+
+ main.output.dir(Collections.<String, Object> singletonMap('builtBy', task), generatedDir)
Review Comment:
Both halves addressed in `62b74b9a3f`.
The task now fails when a hand-maintained copy exists in the module's resources, naming the path and saying to delete it, so the two-copies state cannot be reached silently.
On the second half: `grails-databinding` now applies the convention plugin and its hand-maintained imports file is deleted. The generated file is byte-identical to the one removed, the scan reports no unresolvable classes, and the jar carries the resource exactly once. That also answers the coverage gap you raised on `settings.gradle` — the plugin now has a consumer inside core-only CI, which matters once the example modules move out of it.
##########
grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPlugin.groovy:
##########
@@ -51,15 +72,55 @@ class UrlMappingsGrailsPlugin extends Plugin {
def dependsOn = [core: version]
def loadAfter = ['controllers']
+ def beans = {
+ field('cacheUrls', Boolean).value(Settings.WEB_LINK_GENERATOR_USE_CACHE, '#{null}')
+ field('serverURL', String).value(Settings.SERVER_URL, '#{null}')
+
+ // The two mutually exclusive grailsUrlConverter variants share one bean name; the
+ // @ConditionalOnProperty selects which registers. Its name: attribute must be an inline
+ // constant, so the property names below are literals mirroring Settings.WEB_URL_CONVERTER
Review Comment:
Correct, and fixed in `af64be699c`. `Settings` is an interface, so the constants fold under `@CompileStatic`; `Settings.WEB_URL_CONVERTER` and `Settings.SETTING_CORS_FILTER` are used here now and the comment justifying the literals is gone.
The documentation bullet that sent me to literals in the first place is rewritten too — see my reply on `hookingIntoRuntimeConfiguration.adoc:202`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3679571629
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "bean(...) must end with a factory closure: bean(Type) { ... }");
+ return;
+ }
+ ClosureExpression factory = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ typeAndName.type.getType(),
+ factory.getParameters() == null ? Parameter.EMPTY_ARRAY : factory.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ factory.getCode());
+ beanMethod.addAnnotation(beanAnnotation(typeAndName.name));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = owner.getField(fieldName);
+ if (field != null && field.isStatic() && field.isFinal() &&
+ field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
Review Comment:
Fixed in `9743d3a54e`. Both halves of the diagnosis were right, and your table matched what I reproduced.
The AST lookup now walks interfaces (`findStaticFinalField`, recursing through `getInterfaces()` up the superclass chain), so an interface-declared constant — the shape every `grails.config.Settings` key has — resolves while its owner is still compiling.
One departure worth calling out: I did **not** add `owner.isResolved()`. `DecompiledClassNode` — what the compiler hands you for a class read from a jar — reports itself resolved while still having no loaded `Class`, so the guard alone would not close the hole. The catch now includes `GroovyBugError` explicitly, which covers every node kind. Happy to add the `isResolved()` fast-path on top if you would rather see the intent stated at the call site.
Two tests, both of which fail without the fix: a constant inherited through two same-unit interfaces resolves, and a typo against a same-file constant produces the intended located message instead of `BUG! exception in phase 'canonicalization'`.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "bean(...) must end with a factory closure: bean(Type) { ... }");
+ return;
+ }
+ ClosureExpression factory = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ typeAndName.type.getType(),
+ factory.getParameters() == null ? Parameter.EMPTY_ARRAY : factory.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ factory.getCode());
+ beanMethod.addAnnotation(beanAnnotation(typeAndName.name));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = owner.getField(fieldName);
+ if (field != null && field.isStatic() && field.isFinal() &&
+ field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
+ return value instanceof String ? (String) value : null;
+ }
+ catch (ReflectiveOperationException | RuntimeException | LinkageError ignored) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ private void processMethodStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "method(...) must end with a body closure: method(\"name\", Type) { ... }");
+ return;
+ }
+ ClosureExpression body = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, METHOD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ MethodNode helperMethod = new MethodNode(
+ typeAndName.name,
+ Modifier.PRIVATE,
+ typeAndName.type.getType(),
+ body.getParameters() == null ? Parameter.EMPTY_ARRAY : body.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ body.getCode());
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyGenericAnnotation(helperMethod, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(helperMethod);
+ }
+
+ private static final class TypeAndName {
+ private final ClassExpression type;
+ private final String name;
+
+ TypeAndName(ClassExpression type, String name) {
+ this.type = type;
+ this.name = name;
+ }
+ }
+
+ private TypeAndName parseNameAndType(List<Expression> args, MethodCallExpression call, SourceUnit source,
+ String callName, boolean requireValidIdentifier) {
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ if (args.size() == 2 && args.get(0) instanceof ClassExpression) {
+ addError(call, source, callName + "(...) takes the name before the type: " +
+ callName + "(\"myGreeter\", Greeter), not " + callName + "(Greeter, \"myGreeter\")");
+ }
+ else {
+ addError(call, source, callName + "(...) requires a type, optionally preceded by a name, " +
+ "e.g. " + callName + "(Greeter) or " + callName + "(\"myGreeter\", Greeter)");
+ }
+ return null;
+ }
+ ClassExpression type = (ClassExpression) args.get(args.size() - 1);
+
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(type.getType().getNameWithoutPackage());
+ }
+ else {
+ Expression nameArg = args.get(0);
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, callName + "(name, Type) requires the name to be a String literal, " +
+ "e.g. " + callName + "(\"myGreeter\", Greeter)");
+ return null;
+ }
+ name = (String) nameValue;
+ if (requireValidIdentifier && !isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "\"" + name + "\" is not a valid name: it becomes the generated " +
+ "member's name, so it must be a valid Java identifier");
+ return null;
+ }
+ // Even bean(...), which otherwise allows any Spring name, must reject a blank one:
+ // Spring treats a blank @Bean name as absent and falls back to the method name, so
+ // the name actually written would be silently discarded.
+ if (!requireValidIdentifier && name.isBlank()) {
+ addError(nameArg, source, callName + "(name, Type) requires a non-blank name");
+ return null;
+ }
+ }
+ return new TypeAndName(type, name);
+ }
+
+ private boolean applyQualifier(MethodNode beanMethod, String beanName, MethodCallExpression qualifierCall,
+ List<Expression> args, SourceUnit source) {
+ String name = qualifierCall.getMethodAsString();
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(name)) {
+ AnnotationNode annotation = conditionalOnMissingBeanAnnotation(args, qualifierCall, source);
+ return annotation != null && addAnnotationIfAbsent(beanMethod, qualifierCall, annotation, source);
+ }
+ if (CONDITIONAL_ON_MISSING_BEAN_NAME_CALL.equals(name)) {
+ AnnotationNode annotation = conditionalOnMissingBeanNameAnnotation(args, beanName, qualifierCall, source);
+ return annotation != null && addAnnotationIfAbsent(beanMethod, qualifierCall, annotation, source);
+ }
+ if (PRIMARY_CALL.equals(name) || LAZY_CALL.equals(name)) {
+ if (!args.isEmpty()) {
+ addError(qualifierCall, source, "." + name + "() takes no arguments");
+ return false;
+ }
+ Class<?> annotationType = PRIMARY_CALL.equals(name) ? Primary.class : Lazy.class;
+ return addAnnotationIfAbsent(beanMethod, qualifierCall,
+ new AnnotationNode(ClassHelper.make(annotationType)), source);
+ }
+ // Generates a static factory method - Spring's recommended shape for a
+ // BeanFactoryPostProcessor/BeanPostProcessor bean, which must be creatable without
+ // instantiating its declaring configuration class. The body consequently cannot touch
+ // field(...)/method(...) members, which are instance members of that class.
+ if (STATIC_METHOD_CALL.equals(name)) {
+ if (!args.isEmpty()) {
+ addError(qualifierCall, source, ".staticMethod() takes no arguments");
+ return false;
+ }
+ beanMethod.setModifiers(beanMethod.getModifiers() | Modifier.STATIC);
+ return true;
+ }
+ if (SCOPE_CALL.equals(name)) {
+ return applyScopeQualifier(beanMethod, qualifierCall, args, source);
+ }
+ return applyGenericAnnotation(beanMethod, qualifierCall, args, source);
+ }
+
+ private boolean applyScopeQualifier(MethodNode beanMethod, MethodCallExpression qualifierCall,
+ List<Expression> args, SourceUnit source) {
+ Expression scopeArg = args.size() == 1 ? args.get(0) : null;
+ Object scopeValue = scopeArg instanceof ConstantExpression ? ((ConstantExpression) scopeArg).getValue() : null;
+ if (!(scopeValue instanceof String) || ((String) scopeValue).isEmpty()) {
+ addError(qualifierCall, source, ".scope(...) requires exactly one non-empty String argument, " +
+ "e.g. .scope(\"prototype\")");
+ return false;
+ }
+ AnnotationNode scopeAnnotation = new AnnotationNode(ClassHelper.make(Scope.class));
+ scopeAnnotation.setMember("value", scopeArg);
+ return addAnnotationIfAbsent(beanMethod, qualifierCall, scopeAnnotation, source);
+ }
+
+ private boolean applyGenericAnnotation(AnnotatedNode target, MethodCallExpression qualifierCall,
+ List<Expression> args, SourceUnit source) {
+ MapExpression members = !args.isEmpty() && args.get(0) instanceof MapExpression ? (MapExpression) args.get(0) : null;
+ List<Expression> remaining = members != null ? args.subList(1, args.size()) : args;
+ if (remaining.size() != 1 || !(remaining.get(0) instanceof ClassExpression)) {
+ addError(qualifierCall, source, ".annotate(...) requires an annotation type as its only " +
+ "positional argument, e.g. .annotate(Order, value: 1) or .annotate(ConditionalOnWebApplication)");
+ return false;
+ }
+
+ ClassNode annotationType = ((ClassExpression) remaining.get(0)).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(qualifierCall, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ return false;
+ }
+
+ AnnotationNode annotation = new AnnotationNode(annotationType);
+ if (members != null && !addMembersFromMap(annotation, members, qualifierCall, source)) {
+ return false;
+ }
+ return addAnnotationIfAbsent(target, qualifierCall, annotation, source);
+ }
+
+ private boolean addMembersFromMap(AnnotationNode annotation, MapExpression members,
+ MethodCallExpression qualifierCall, SourceUnit source) {
+ for (MapEntryExpression entry : members.getMapEntryExpressions()) {
+ Object keyValue = entry.getKeyExpression() instanceof ConstantExpression ?
+ ((ConstantExpression) entry.getKeyExpression()).getValue() : null;
+ if (!(keyValue instanceof String)) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() +
+ "(...) attribute names must be simple identifiers, e.g. .annotate(Order, value: 1)");
+ return false;
+ }
+ annotation.setMember((String) keyValue, entry.getValueExpression());
Review Comment:
Fixed in `9743d3a54e`. `addMembersFromMap` now runs every attribute value through `resolveStringConstant` (`foldStringValue`), so `.annotate(...)` and `.value(...)` agree. Non-String values — class literals, numbers, enum constants, arrays — are left untouched.
The fixture is duplicated under `@CompileStatic` as you asked, and it fails without the fix, so the general rule its `given:` block claims is now actually demonstrated for the mode every conversion in this PR uses.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
Review Comment:
Fixed in `9743d3a54e`. The walk now rejects a root call whose receiver is another `MethodCallExpression` rather than the implicit `this`, so `field('suffix', String).bean('greeter', String) { }` is a compile error naming both calls instead of silently dropping the left-hand declaration.
Two rows added to the malformed-statement table, one for each direction.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "bean(...) must end with a factory closure: bean(Type) { ... }");
+ return;
+ }
+ ClosureExpression factory = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ typeAndName.type.getType(),
+ factory.getParameters() == null ? Parameter.EMPTY_ARRAY : factory.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ factory.getCode());
+ beanMethod.addAnnotation(beanAnnotation(typeAndName.name));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = owner.getField(fieldName);
+ if (field != null && field.isStatic() && field.isFinal() &&
+ field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
+ return value instanceof String ? (String) value : null;
+ }
+ catch (ReflectiveOperationException | RuntimeException | LinkageError ignored) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ private void processMethodStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "method(...) must end with a body closure: method(\"name\", Type) { ... }");
+ return;
+ }
+ ClosureExpression body = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, METHOD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ MethodNode helperMethod = new MethodNode(
+ typeAndName.name,
+ Modifier.PRIVATE,
+ typeAndName.type.getType(),
+ body.getParameters() == null ? Parameter.EMPTY_ARRAY : body.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ body.getCode());
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyGenericAnnotation(helperMethod, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(helperMethod);
+ }
+
+ private static final class TypeAndName {
+ private final ClassExpression type;
+ private final String name;
+
+ TypeAndName(ClassExpression type, String name) {
+ this.type = type;
+ this.name = name;
+ }
+ }
+
+ private TypeAndName parseNameAndType(List<Expression> args, MethodCallExpression call, SourceUnit source,
+ String callName, boolean requireValidIdentifier) {
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ if (args.size() == 2 && args.get(0) instanceof ClassExpression) {
+ addError(call, source, callName + "(...) takes the name before the type: " +
+ callName + "(\"myGreeter\", Greeter), not " + callName + "(Greeter, \"myGreeter\")");
+ }
+ else {
+ addError(call, source, callName + "(...) requires a type, optionally preceded by a name, " +
+ "e.g. " + callName + "(Greeter) or " + callName + "(\"myGreeter\", Greeter)");
+ }
+ return null;
+ }
+ ClassExpression type = (ClassExpression) args.get(args.size() - 1);
+
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(type.getType().getNameWithoutPackage());
Review Comment:
Fixed in `9743d3a54e`. The check moved so it covers the convention-derived name too, with a message that names the type it was derived from and suggests an explicit one. `field(Boolean)`, `field(Long)` and `method(Class)` are now rejected the same way `field('boolean', Boolean)` already was. Two table rows.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
Review Comment:
Fixed in `9743d3a54e` — `removeField(BEANS_PROPERTY)` in place of mutating `getFields()`. Both call sites go through the one helper, so the empty-block early return is covered as well.
Test asserts the compiled class carries no `beans` field, and that reaching the stale member now fails as a `MissingPropertyException` rather than `NoSuchFieldError`.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
Review Comment:
Fixed in `9743d3a54e` — propagated, not rejected. `applyStaticCompilation` now tries `CompileStatic` with `StaticCompileTransformation` and falls back to `TypeChecked` with `StaticTypesTransformation`. Test: a `@TypeChecked` plugin whose bean body contains an assignment error now fails to compile, where it previously compiled unchecked.
Agreed on `@GrailsCompileStatic`/`@GrailsTypeChecked` — `@AnnotationCollector` has already expanded both by canonicalization, so matching the two Groovy annotations covers all four spellings.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
Review Comment:
Fixed in `9743d3a54e`. Positions are copied at five points: the sibling `ClassNode` from the plugin class, bean and helper `MethodNode`s and the `FieldNode` from their DSL statement, and every `AnnotationNode` at the `addAnnotationIfAbsent` choke point, which covers the qualifiers and `.annotate(...)` together.
Test compiles `.annotate(Order, valu: 1)` and asserts the message no longer contains `line -1`.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
Review Comment:
Yes, that is what was intended, and it is what the code does now (`9743d3a54e`). Only a positional type or a type-bearing attribute discriminates; a map of nothing but `name:` and/or `search:` is treated exactly like the bare form. An argument shape the check does not model stays lenient rather than erroring.
Two table rows, `name:` alone and `name:` + `search:`. Both fail without the fix.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3679574753
##########
grails-cache/build.gradle:
##########
@@ -49,6 +49,7 @@ dependencies {
api "org.codehaus.gpars:gpars:$gparsVersion"
api "com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:$concurrentlinkedhashmapLruVersion"
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`.
##########
grails-databinding/build.gradle:
##########
@@ -38,6 +38,7 @@ dependencies {
implementation platform(project(':grails-bom'))
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`.
##########
grails-domain-class/build.gradle:
##########
@@ -38,6 +38,7 @@ dependencies {
implementation platform(project(':grails-bom'))
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`.
##########
grails-i18n/build.gradle:
##########
@@ -41,6 +41,8 @@ dependencies {
api project(':grails-web-core')
api 'org.apache.groovy:groovy'
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`.
##########
grails-url-mappings/build.gradle:
##########
@@ -43,6 +43,8 @@ dependencies {
api 'org.apache.groovy:groovy'
api 'org.springframework.boot:spring-boot-servlet'
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`.
##########
grails-gsp/grails-sitemesh3/build.gradle:
##########
@@ -52,6 +52,7 @@ dependencies {
api project(':grails-core')
implementation 'org.apache.groovy:groovy'
+ implementation project(':grails-beans-dsl')
Review Comment:
Removed in `138d014236`.
##########
grails-mail/build.gradle:
##########
@@ -76,10 +76,14 @@ dependencies {
compileOnly 'org.springframework.boot:spring-boot-autoconfigure' // @AutoConfiguration, @ConditionalOnProperty, @ConfigurationProperties
compileOnly 'org.apache.groovy:groovy' // Provided as this is a Grails plugin
compileOnly 'org.slf4j:slf4j-api' // @Slf4j
+ compileOnly project(':grails-beans-dsl') // comp: @GrailsBeans
Review Comment:
Removed in `138d014236`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3686892809
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1354 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import groovy.transform.TypeChecked;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.GroovyBugError;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.ArgumentListExpression;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.expr.VariableExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.EmptyStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.ReturnStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.StaticTypesTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained. Its parameters are always the DSL closure's own, annotations
+ * included. Its body is the closure's, except where that body is empty - or the closure is omitted
+ * altogether - in which case a {@code new Type(...)} call over those same parameters is synthesised
+ * instead, leaving the compiler to select the constructor from their types exactly as it would for a
+ * body written out by hand. The generated method's name is an implementation detail: it matches the
+ * bean name when that is a usable Java identifier not already taken by an existing or generated
+ * member, and falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name
+ * like {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString}
+ * never overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ // An empty block is a no-op, not an error - an empty @Configuration class is legal in Spring
+ // and an empty resources.groovy is legal in Grails, so having nothing to declare should not
+ // fail the build. Returning before the sibling is created matters: generating it would leave
+ // a bean-less class holding the @AutoConfiguration and @Conditional* annotations moved off
+ // the plugin, which is worse than doing nothing. Only the DSL scaffolding is stripped.
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ if (statements.isEmpty()) {
+ removeBeansProperty(classNode, beansProperty);
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ removeBeansProperty(classNode, beansProperty);
+ }
+
+ private void removeBeansProperty(ClassNode classNode, PropertyNode beansProperty) {
+ classNode.getProperties().remove(beansProperty);
+ // removeField, not getFields().remove: the latter leaves ClassNode's own fieldIndex entry
+ // behind, so another member still referring to 'beans' type-checks and compiles to a
+ // getfield against a field that is never emitted, failing with NoSuchFieldError at runtime.
+ classNode.removeField(BEANS_PROPERTY);
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ // Without a position, anything Groovy later reports against a generated node - a sibling
+ // name clash, a typo in .annotate(...) - is reported at line -1, column -1.
+ sibling.setSourcePosition(pluginClass);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // The bean bodies are lifted onto a class the normal transform pipeline no longer visits, so
+ // whichever of these the author put on the plugin has to be re-applied here or the bodies are
+ // silently left unchecked. @GrailsCompileStatic and @GrailsTypeChecked need no handling of their
+ // own: @AnnotationCollector has already expanded them by canonicalization.
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ if (compilationUnit == null) {
+ return;
+ }
+ if (applyStaticTypesTransformation(pluginClass, sibling, source,
+ CompileStatic.class, new StaticCompileTransformation())) {
+ return;
+ }
+ applyStaticTypesTransformation(pluginClass, sibling, source,
+ TypeChecked.class, new StaticTypesTransformation());
+ }
+
+ private boolean applyStaticTypesTransformation(ClassNode pluginClass, ClassNode sibling, SourceUnit source,
+ Class<? extends java.lang.annotation.Annotation> annotationType, StaticTypesTransformation transformation) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(annotationType));
+ if (annotations.isEmpty()) {
+ return false;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(annotationType));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ siblingAnnotation.setSourcePosition(sourceAnnotation);
+ sibling.addAnnotation(siblingAnnotation);
+
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ return true;
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && discriminatesByType(args)) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ // @ConditionalOnMissingBean attributes that say nothing about a *type*. Where duplicates share
+ // one bean name - the only situation validateSharedBeanNames runs in - a name: or search: is
+ // identical on each of them and so can no more tell them apart than the bare form can.
+ private static final Set<String> NON_DISCRIMINATING_MISSING_BEAN_ATTRIBUTES = Set.of("name", "search");
+
+ private boolean discriminatesByType(List<Expression> args) {
+ boolean sawSomething = false;
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression) {
+ return true;
+ }
+ if (!(arg instanceof MapExpression)) {
+ // an argument shape this method does not model - stay lenient rather than reject
+ return true;
+ }
+ for (MapEntryExpression entry : ((MapExpression) arg).getMapEntryExpressions()) {
+ Object key = entry.getKeyExpression() instanceof ConstantExpression ?
+ ((ConstantExpression) entry.getKeyExpression()).getValue() : null;
+ if (!(key instanceof String) || !NON_DISCRIMINATING_MISSING_BEAN_ATTRIBUTES.contains(key)) {
+ return true;
+ }
+ sawSomething = true;
+ }
+ }
+ return !sawSomething && !args.isEmpty();
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ // The walk above stops at the first root call name it meets, so without this a root
+ // statement chained onto another - field("suffix", String).bean("greeter", String) { } -
+ // parses as one statement and the left-hand declaration is silently dropped.
+ if (!baseCall.isImplicitThis() && baseCall.getObjectExpression() instanceof MethodCallExpression) {
+ addError(statement, source, baseCall.getMethodAsString() + "(...) cannot be chained onto " +
+ ((MethodCallExpression) baseCall.getObjectExpression()).getMethodAsString() +
+ "(...) - each bean(...), field(...) and method(...) declaration is its own statement");
+ return;
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ // The factory closure is optional: bean(Type) with no body declares a bean that is just its
+ // own no-argument construction, which is by far the most common shape and reads as noise
+ // when spelled out as bean(Type) { new Type() }.
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ ClosureExpression factory = !closureCallArgs.isEmpty() &&
+ closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression ?
+ (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1) : null;
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (factory != null && baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ ClassNode beanType = typeAndName.type.getType();
+ // A closure whose body is empty declares construction too, from its own parameters: the
+ // parameters say what is injected, and the generated body is the constructor call the author
+ // would otherwise have written out. bean(Type) { } with no parameters is bean(Type).
+ boolean constructsDeclaredType = factory == null || isEmpty(factory.getCode());
+ if (constructsDeclaredType && (beanType.isInterface() || Modifier.isAbstract(beanType.getModifiers()))) {
+ addError(baseCall, source, "bean(" + beanType.getNameWithoutPackage() + ") with no factory closure body " +
+ "constructs the declared type, which cannot be done for an interface or abstract class - " +
+ "give it a body: bean(" + beanType.getNameWithoutPackage() + ") { new SomeImplementation() }");
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ Parameter[] beanParameters = factory == null || factory.getParameters() == null ?
+ Parameter.EMPTY_ARRAY : factory.getParameters();
+ Statement beanBody = constructsDeclaredType ?
Review Comment:
Fixed in `a4deb3d2cd`. Reproduced exactly as described — `BUG!` at line -1 for the empty-body form, against a located "Cannot find matching constructor" for the hand-written equivalent.
The position now goes on the whole synthesized construction: the `ConstructorCallExpression`, its argument list, each `VariableExpression`, and the enclosing `ReturnStatement`. Both spellings now report
```
[Static type checking] - Cannot find matching constructor NeedsString(java.lang.Integer).
@ line 15, column 13.
bean(NeedsString) { Integer n ->
^
```
Two tests, one per spelling, asserting the message and that it contains neither `line -1` nor `BUG!`.
##########
grails-doc/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc:
##########
@@ -119,6 +119,148 @@ class I18nGrailsPlugin extends Plugin {
A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.
+==== Compiling Bean Definitions into a Spring Boot AutoConfiguration
+
+
+`beanRegistrar()` and `doWithSpring` register beans at a single, fixed point in startup: before Spring Boot processes any `{springbootapi}org/springframework/boot/autoconfigure/AutoConfiguration.html[AutoConfiguration]`. That is enough for a bean to win against a Boot default guarded by `@ConditionalOnMissingBean`, but it cannot express ordering *relative to a specific* auto-configuration — running before `WebMvcAutoConfiguration` but after `MessageSourceAutoConfiguration`, say, regardless of where those two land in Boot's overall sort. Only a real `AutoConfiguration` class can declare that ordering, via `@AutoConfiguration(before = ..., after = ...)`.
+
+The link:{api}grails/compiler/beans/GrailsBeans.html[GrailsBeans] annotation lets you author bean definitions with DSL syntax similar to the classic Beans DSL, while compiling them at build time into genuine `@Bean` factory methods on a plain `AutoConfiguration` class — no closures, and nothing DSL-specific, survive into the compiled bytecode. Declare a class whose `beans` property is a closure of `bean(["name", ] Type) { ... }` statements:
+
+NOTE: On a `*GrailsPlugin.groovy` plugin descriptor or an application's `Application` class the annotation is implicit — a `beans` property is compiled automatically, the same way `doWithSpring` and `watchedResources` are conventions rather than annotated members. `@GrailsBeans` is written out only on a standalone class, as in the first example below. A class with no `beans` property is untouched.
+
+[source,groovy]
+----
+import grails.compiler.beans.GrailsBeans
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration
+import org.springframework.context.MessageSource
+import org.springframework.context.support.ReloadableResourceBundleMessageSource
+import org.springframework.web.servlet.i18n.CookieLocaleResolver
+import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
+
+@GrailsBeans
+@AutoConfiguration(before = [MessageSourceAutoConfiguration, WebMvcAutoConfiguration])
+class I18nBeans {
+
+ def beans = {
+ bean('messageSource', ReloadableResourceBundleMessageSource) {
+ new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
+ }
+
+ bean('localeResolver', CookieLocaleResolver).conditionalOnMissingBean(CookieLocaleResolver) {
+ new CookieLocaleResolver('locale')
+ }
+
+ bean('localeChangeInterceptor', LocaleChangeInterceptor) { MessageSource messageSource ->
+ new LocaleChangeInterceptor(paramName: 'lang')
+ }
+ }
+}
+----
+
+Each `bean(["name", ] Type)` statement compiles to a public method returning the declared type and annotated `@Bean("name")`. The generated method's name is an implementation detail — Spring resolves the bean by its `@Bean("name")` value, never by the method name. It matches the bean name when that is a valid Java identifier not already taken by an existing member (declared, inherited, or defined elsewhere in the DSL — a bean named `toString` will not override `Object.toString()`); otherwise a synthesized `<type>$N` name (`service$0`, `service$1`, ...) is used instead, so any legal, non-blank Spring bean name compiles:
+
+* The bean name defaults to the decapitalized simple class name when omitted.
+* The factory closure itself may be omitted when a bean is nothing but its own no-argument construction: `bean(XmlDataBindingSourceCreator)` declares exactly what `bean(XmlDataBindingSourceCreator) { new XmlDataBindingSourceCreator() }` does, without restating the type twice. It takes an explicit name (`bean('xmlCreator', XmlDataBindingSourceCreator)`) and chains the qualifiers below just as the closure form does (`bean(Widget).primary().lazy()`). The declared type is the one constructed, so it must be concrete and have an accessible no-argument constructor; for an interface or abstract type, give the bean a body naming the implementation.
+* Leaving the closure's *body* empty means the same thing for a bean with dependencies: the parameters say what is injected, and the constructor call is generated. `bean('validateableConstraintsEvaluator', DefaultConstraintEvaluatorFactoryBean).lazy() { List<MessageSource> messageSources, @Qualifier('grailsDomainClassMappingContext') MappingContext mappingContext, GrailsApplication grailsApplication -> }` generates a method with exactly those three parameters whose body is `new DefaultConstraintEvaluatorFactoryBean(messageSources, mappingContext, grailsApplication)` — the parameters in the order written. Which constructor that selects is decided by the compiler from the parameter types, exactly as for a body you wrote yourself, so nothing here depends on the declared type's other constructors. A body is still needed whenever construction is more than passing the parameters straight through — `new ConfigProperties(grailsApplication.config)`, or anything followed by `.tap { }`.
+* The same bean name may be declared by more than one `bean(...)` statement — the standard Spring Boot pattern for mutually exclusive variants of one bean, such as the framework's own `grailsUrlConverter` selected by `@ConditionalOnProperty` — provided every declaration with the name carries its own discriminating condition (such as `.annotate(ConditionalOnProperty, ...)`), so that at most one of them registers at runtime. Duplicating a bean name without that is a compile-time error, since Spring would keep the first definition and silently skip the rest.
+* Chaining `.conditionalOnMissingBean(...)` adds a `@ConditionalOnMissingBean` annotation to the generated method, matching Spring Boot's usual back-off semantics. It takes positional types (`.conditionalOnMissingBean(Greeter)`), the annotation's own named attributes (`.conditionalOnMissingBean(name: 'localeResolver', search: SearchStrategy.CURRENT)`), or both. With no arguments at all it compiles to the bare annotation, letting Spring Boot infer the back-off type from the method's return type — the recommended form when a bean simply backs off its own type, since `bean(AvailableLocaleResolver).conditionalOnMissingBean()` already says everything `.conditionalOnMissingBean(AvailableLocaleResolver)` would repeat.
+* Chaining `.conditionalOnMissingBeanName(...)` is the name-based counterpart: "register this bean unless a bean with *this bean's name* already exists". The condition's `name` member is set from the bean's own (explicit or convention-derived) name, so `bean(MessageSource).conditionalOnMissingBeanName(search: SearchStrategy.CURRENT) { ... }` states `messageSource` once and it feeds both `@Bean` and the condition — the two strings the explicit form has to keep in sync cannot diverge. It accepts the annotation's other attributes (`search:`, `ignored:`, ...) but rejects `name:` and types, which would contradict its purpose; use `.conditionalOnMissingBean(...)` for those.
+* Chaining `.primary()`, `.lazy()`, and/or `.scope("name")` adds `@Primary`, `@Lazy`, and `@Scope("name")` respectively.
+* Chaining `.staticMethod()` makes the generated factory method `static` — Spring's recommended shape for `BeanFactoryPostProcessor` and `BeanPostProcessor` beans, which must be creatable without instantiating their declaring configuration class. A static bean's closure cannot reference `field(...)` or `method(...)` members, since those are instance members; under `@CompileStatic` that mistake is a compile error.
+* Chaining `.annotate(AnnotationType[, attr: value, ...])` attaches any other single-valued annotation directly — any `@Conditional*` (built-in or a custom `Condition`), `@Order`, `@DependsOn`, or anything else a hand-written `@Bean` method could carry. It's repeatable, so several different annotations can be chained onto the same bean: `bean('special', Special).annotate(Order, value: 1).annotate(ConditionalOnProperty, prefix: 'myapp', name: 'enabled', havingValue: 'true') { ... }`.
+* Any combination of the above can be chained together, in any order — for example `bean('slowGreeter', SlowGreeter).lazy().scope('prototype') { ... }`.
+* Typed closure parameters (`{ MessageSource messageSource -> ... }`) become the generated method's parameters, so other beans are injected the same way a hand-written `@Bean` method would declare them — and a parameter-level annotation such as `{ @Qualifier('special') Greeter g -> ... }` carries straight through too, since the closure's own parameters become the generated method's parameters directly.
+
+Two more statement kinds can appear inside `beans { }` alongside `bean(...)`, for state and logic shared across bean methods — the same role a hand-written `@Configuration` class's own fields and private methods play:
+
+* `field(["name", ] Type)`, optionally chained with `.value(...)` and/or (repeatably) `.annotate(AnnotationType[, attr: value, ...])`, declares a private field on the generated class. The usual case is injected configuration, and `.value(...)` covers it directly: `field('encoding', String).value('grails.views.gsp.encoding', 'UTF-8')` compiles to `@Value("${grails.views.gsp.encoding:UTF-8}")`. The two-argument form takes a config key and default — and because the DSL builds the placeholder itself, the key may be a bare constant reference (`.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')`), the one shape a directly-written annotation value can't accept. The one-argument form takes a bare config key with no default — `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` — while a string already containing a `${...}` placeholder or a `#{...}` SpEL expression passes through verbatim: `.value('#{T(java.lang.Runtime).getRuntime().avail
ableProcessors()}')`.
+* `method(["name", ] Type) { ... }`, chainable with `.annotate(...)` only (`.value(...)` is field-specific), declares a private helper method the same way `bean(...)` declares a public one — typed closure parameters become method parameters, and the closure body becomes the method body.
+
+Both are ordinary private members of the generated class, so a `bean(...)` closure reads a `field(...)` or calls a `method(...)` exactly like a hand-written `@Bean` method would reference a sibling field or method on its own class:
+
+[source,groovy]
+----
+field('suffix', String).value('myapp.greeting-suffix', '!')
+
+method('buildGreeting', String) { String name ->
+ "Hello, ${name}${suffix}"
+}
+
+bean('greeting', Greeting) {
+ new Greeting(buildGreeting('World'))
+}
+----
+
+Because the result is an ordinary `AutoConfiguration` class, it must be registered the same way any Spring Boot auto-configuration is: listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`. Modules built as part of this project can apply the `org.apache.grails.buildsrc.autoconfiguration-imports` Gradle convention plugin to generate that file automatically, by scanning the module's own compiled classes for `@AutoConfiguration` at build time. Projects outside this build register the class the same way any hand-written `AutoConfiguration` is registered — by listing it in that file directly.
+
+NOTE: `@GrailsBeans` does not require extending `Plugin` at all — it produces a plain Spring Boot `AutoConfiguration`, so it can be used by any Spring Boot module, not just a Grails plugin descriptor. Applications can use it too, including directly on the `Application` class — where no imports-file registration is needed, since Spring Boot processes the application class itself — see link:spring.html#springdslAdditional[Configuring Additional Beans]. Within a plugin, reach for it specifically when a bean's registration needs to be ordered against a particular other auto-configuration; otherwise `beanRegistrar()` remains the recommended way to register beans from a `Plugin`.
+
+The DSL still covers a narrower surface than `doWithSpring(BeanBuilder)`:
+
+* Each top-level statement inside `beans { }` must be exactly `bean(...)`, `field(...)`, or `method(...)`, with their respective chaining — an `if`, a `for` loop, or any other imperative Groovy directly inside `beans { }` is a compile-time error, not a runtime one. Note that this is about the DSL's own top-level statements, not the bodies of `bean(...)`/`method(...)` closures themselves, which accept arbitrary Groovy, subject only to what is reachable from the generated class (see the last bullet below) — and `field(...)`/`method(...)` already cover the common reasons to want shared state or logic in the first place.
+* `.annotate(...)` attribute values must be compile-time constants: strings, numbers, booleans, class literals, enum constants, or arrays of these. A bare constant *reference* counts, and so does a *concatenation* of them — `.annotate(Value, value: '${' + Settings.I18N_LOCALE_RESOLVER + ':session}')` folds, `@CompileStatic` included, the same way `.value(...)` folds its arguments. The one shape that does not fold is a `static final` declared on a Groovy *class*: that is a property with a generated getter, and `@CompileStatic` rewrites the reference into a call to it. An interface's constants are real `public static final` fields and fold correctly — which is every `grails.config.Settings` key. An attribute that itself takes a nested annotation as its value isn't supported.
Review Comment:
You're right, and this bullet has now been wrong twice. The previous correction removed the concatenation claim but kept this exception on the strength of your earlier report — which predated the fix that changed the behaviour. I should have tested it rather than carrying it forward.
Confirmed all three shapes fold with the constant on a Groovy class under `@CompileStatic`: `.value(KEY, 'x')` → `${probe.key:x}`, the concatenation → `${probe.key:y}`, a bare reference → `probe.key`.
Rewritten in `f31d57061f` to say what actually holds — values must resolve to a compile-time constant, resolution happens before `@CompileStatic` runs, so interface-versus-class makes no difference — with three unrolled cases so it cannot drift again. PR description updated to match.
##########
grails-doc/src/en/guide/upgrading/upgrading80x.adoc:
##########
@@ -1600,7 +1600,19 @@ This was introduced during the Grails 7.1 plugin-loading changes and remains req
| `grails-domain-class`
| `ConstraintEvaluatorAdapter` and `GrailsDomainClassAutoConfiguration.constraintsEvaluator(...)`
-| Code that imported the auto-configuration method should use the current `validateableConstraintsEvaluator(...)` bean path and the datastore constraint evaluator APIs.
+| Code that imported the auto-configuration method should use the current `validateableConstraintsEvaluator(...)` bean path and the datastore constraint evaluator APIs. The auto-configuration itself is now named `org.grails.plugins.domain.DomainClassAutoConfiguration`, following the `*GrailsPlugin` -> `*AutoConfiguration` convention; update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name.
+
+| `grails-core`
+| `org.grails.plugins.core.CoreAutoConfiguration`
+| Now `org.grails.plugins.CoreAutoConfiguration`. The class is generated beside the plugin descriptor that declares its beans, and `CoreGrailsPlugin` lives in `org.grails.plugins`, so the simple name is unchanged but the package is not. Update any `@EnableAutoConfiguration(exclude = ...)`, `spring.autoconfigure.exclude`, or `@AutoConfigureAfter(name = ...)` entry naming the old package. Spring Boot only reports an invalid exclude for a class still on the classpath, so a stale entry is silently ignored rather than reported, and the beans it was meant to suppress are registered anyway.
+
+| `grails-cache`
+| `grails.plugin.cache.GrailsCacheAutoConfiguration`
+| Now `grails.plugin.cache.CacheAutoConfiguration`, following the `*GrailsPlugin` -> `*AutoConfiguration` convention. Update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name; the same silent-ignore applies as above.
+
+| `grails-databinding`
+| `org.grails.plugins.databinding.DataBindingConfiguration`
+| Now `org.grails.plugins.databinding.DataBindingAutoConfiguration`. It was registered as an auto-configuration while named only `*Configuration`; the name now says what it is. Update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name; the same silent-ignore applies as above.
Review Comment:
Agreed it matters more than the renames. Added as section 39 in `4e51a2556a`, covering the working-directory probe, which deployment shapes it affected, and the two things to check before upgrading: a duplicate bean name that now fails startup, and an injection point that was unambiguous becoming ambiguous.
Noted that `grails.spring.bean.packages` appears only in the Application Properties reference, so there is nothing to cross-reference.
The section is numbered 39 after the duplicate `38.`s. Those, and a duplicate `34.`, are both on `8.0.x` — I checked — so renumbering belongs in its own PR against `8.0.x` rather than as seven unrelated heading changes here.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1354 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import groovy.transform.TypeChecked;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.GroovyBugError;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.ArgumentListExpression;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.expr.VariableExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.EmptyStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.ReturnStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.StaticTypesTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained. Its parameters are always the DSL closure's own, annotations
+ * included. Its body is the closure's, except where that body is empty - or the closure is omitted
+ * altogether - in which case a {@code new Type(...)} call over those same parameters is synthesised
+ * instead, leaving the compiler to select the constructor from their types exactly as it would for a
+ * body written out by hand. The generated method's name is an implementation detail: it matches the
+ * bean name when that is a usable Java identifier not already taken by an existing or generated
+ * member, and falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name
+ * like {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString}
+ * never overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ // An empty block is a no-op, not an error - an empty @Configuration class is legal in Spring
+ // and an empty resources.groovy is legal in Grails, so having nothing to declare should not
+ // fail the build. Returning before the sibling is created matters: generating it would leave
+ // a bean-less class holding the @AutoConfiguration and @Conditional* annotations moved off
+ // the plugin, which is worse than doing nothing. Only the DSL scaffolding is stripped.
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ if (statements.isEmpty()) {
+ removeBeansProperty(classNode, beansProperty);
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ removeBeansProperty(classNode, beansProperty);
+ }
+
+ private void removeBeansProperty(ClassNode classNode, PropertyNode beansProperty) {
+ classNode.getProperties().remove(beansProperty);
+ // removeField, not getFields().remove: the latter leaves ClassNode's own fieldIndex entry
+ // behind, so another member still referring to 'beans' type-checks and compiles to a
+ // getfield against a field that is never emitted, failing with NoSuchFieldError at runtime.
+ classNode.removeField(BEANS_PROPERTY);
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ // Without a position, anything Groovy later reports against a generated node - a sibling
+ // name clash, a typo in .annotate(...) - is reported at line -1, column -1.
+ sibling.setSourcePosition(pluginClass);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // The bean bodies are lifted onto a class the normal transform pipeline no longer visits, so
+ // whichever of these the author put on the plugin has to be re-applied here or the bodies are
+ // silently left unchecked. @GrailsCompileStatic and @GrailsTypeChecked need no handling of their
+ // own: @AnnotationCollector has already expanded them by canonicalization.
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ if (compilationUnit == null) {
+ return;
+ }
+ if (applyStaticTypesTransformation(pluginClass, sibling, source,
+ CompileStatic.class, new StaticCompileTransformation())) {
+ return;
+ }
+ applyStaticTypesTransformation(pluginClass, sibling, source,
+ TypeChecked.class, new StaticTypesTransformation());
+ }
+
+ private boolean applyStaticTypesTransformation(ClassNode pluginClass, ClassNode sibling, SourceUnit source,
+ Class<? extends java.lang.annotation.Annotation> annotationType, StaticTypesTransformation transformation) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(annotationType));
+ if (annotations.isEmpty()) {
+ return false;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(annotationType));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ siblingAnnotation.setSourcePosition(sourceAnnotation);
+ sibling.addAnnotation(siblingAnnotation);
+
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ return true;
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && discriminatesByType(args)) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ // @ConditionalOnMissingBean attributes that say nothing about a *type*. Where duplicates share
+ // one bean name - the only situation validateSharedBeanNames runs in - a name: or search: is
+ // identical on each of them and so can no more tell them apart than the bare form can.
+ private static final Set<String> NON_DISCRIMINATING_MISSING_BEAN_ATTRIBUTES = Set.of("name", "search");
+
+ private boolean discriminatesByType(List<Expression> args) {
+ boolean sawSomething = false;
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression) {
+ return true;
+ }
+ if (!(arg instanceof MapExpression)) {
+ // an argument shape this method does not model - stay lenient rather than reject
+ return true;
+ }
+ for (MapEntryExpression entry : ((MapExpression) arg).getMapEntryExpressions()) {
+ Object key = entry.getKeyExpression() instanceof ConstantExpression ?
+ ((ConstantExpression) entry.getKeyExpression()).getValue() : null;
+ if (!(key instanceof String) || !NON_DISCRIMINATING_MISSING_BEAN_ATTRIBUTES.contains(key)) {
+ return true;
+ }
+ sawSomething = true;
+ }
+ }
+ return !sawSomething && !args.isEmpty();
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ // The walk above stops at the first root call name it meets, so without this a root
+ // statement chained onto another - field("suffix", String).bean("greeter", String) { } -
+ // parses as one statement and the left-hand declaration is silently dropped.
+ if (!baseCall.isImplicitThis() && baseCall.getObjectExpression() instanceof MethodCallExpression) {
+ addError(statement, source, baseCall.getMethodAsString() + "(...) cannot be chained onto " +
+ ((MethodCallExpression) baseCall.getObjectExpression()).getMethodAsString() +
+ "(...) - each bean(...), field(...) and method(...) declaration is its own statement");
+ return;
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ // The factory closure is optional: bean(Type) with no body declares a bean that is just its
+ // own no-argument construction, which is by far the most common shape and reads as noise
+ // when spelled out as bean(Type) { new Type() }.
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ ClosureExpression factory = !closureCallArgs.isEmpty() &&
+ closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression ?
+ (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1) : null;
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (factory != null && baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ ClassNode beanType = typeAndName.type.getType();
+ // A closure whose body is empty declares construction too, from its own parameters: the
+ // parameters say what is injected, and the generated body is the constructor call the author
+ // would otherwise have written out. bean(Type) { } with no parameters is bean(Type).
+ boolean constructsDeclaredType = factory == null || isEmpty(factory.getCode());
+ if (constructsDeclaredType && (beanType.isInterface() || Modifier.isAbstract(beanType.getModifiers()))) {
+ addError(baseCall, source, "bean(" + beanType.getNameWithoutPackage() + ") with no factory closure body " +
+ "constructs the declared type, which cannot be done for an interface or abstract class - " +
+ "give it a body: bean(" + beanType.getNameWithoutPackage() + ") { new SomeImplementation() }");
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ Parameter[] beanParameters = factory == null || factory.getParameters() == null ?
+ Parameter.EMPTY_ARRAY : factory.getParameters();
+ Statement beanBody = constructsDeclaredType ?
+ new ReturnStatement(new ConstructorCallExpression(beanType, constructorArguments(beanParameters))) :
+ factory.getCode();
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ beanType,
+ beanParameters,
+ ClassNode.EMPTY_ARRAY,
+ beanBody);
+ beanMethod.setSourcePosition(baseCall);
+ beanMethod.addAnnotation(withPosition(beanAnnotation(typeAndName.name), baseCall));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (factory != null && qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private boolean isEmpty(Statement code) {
+ return code == null || code instanceof EmptyStatement ||
+ (code instanceof BlockStatement && ((BlockStatement) code).getStatements().isEmpty());
+ }
+
+ /**
+ * The closure's parameters, passed straight through as the constructor's arguments. Which
+ * constructor that selects is left to the compiler, resolved from these argument types exactly as
+ * it would be for a hand-written {@code new Type(...)} - nothing here reads the declared type's
+ * constructors, so adding one cannot change what this bean injects.
+ */
+ private ArgumentListExpression constructorArguments(Parameter[] parameters) {
+ ArgumentListExpression arguments = new ArgumentListExpression();
+ for (Parameter parameter : parameters) {
+ arguments.addExpression(new VariableExpression(parameter));
+ }
+ return arguments;
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+ field.setSourcePosition(baseCall);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = findStaticFinalField(owner, fieldName, new HashSet<>());
+ if (field != null && field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ // The reflective fallback needs a loaded Class, which a ClassNode from this same
+ // compilation unit does not have - getTypeClass() would throw GroovyBugError, an
+ // AssertionError that no catch below would hold, aborting the compilation with an
+ // internal compiler error instead of the located message the caller reports.
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
+ return value instanceof String ? (String) value : null;
+ }
+ catch (ReflectiveOperationException | RuntimeException | LinkageError | GroovyBugError ignored) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ // ClassNode.getField walks superclasses but not interfaces, so a constant declared on an
+ // implemented interface - the shape every grails.config.Settings key has - is invisible to it
+ // while the owner is still being compiled.
+ private FieldNode findStaticFinalField(ClassNode owner, String fieldName, Set<String> visited) {
+ for (ClassNode type = owner; type != null; type = type.getSuperClass()) {
+ if (!visited.add(type.getName())) {
+ return null;
+ }
+ FieldNode declared = type.getDeclaredField(fieldName);
+ if (declared != null && declared.isStatic() && declared.isFinal()) {
+ return declared;
+ }
+ for (ClassNode implemented : type.getInterfaces()) {
+ FieldNode inherited = findStaticFinalField(implemented, fieldName, visited);
+ if (inherited != null) {
+ return inherited;
+ }
+ }
+ }
+ return null;
+ }
+
+ private void processMethodStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "method(...) must end with a body closure: method(\"name\", Type) { ... }");
+ return;
+ }
+ ClosureExpression body = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, METHOD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ MethodNode helperMethod = new MethodNode(
+ typeAndName.name,
+ Modifier.PRIVATE,
+ typeAndName.type.getType(),
+ body.getParameters() == null ? Parameter.EMPTY_ARRAY : body.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ body.getCode());
+ helperMethod.setSourcePosition(baseCall);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyGenericAnnotation(helperMethod, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(helperMethod);
+ }
+
+ private static final class TypeAndName {
+ private final ClassExpression type;
+ private final String name;
+
+ TypeAndName(ClassExpression type, String name) {
+ this.type = type;
+ this.name = name;
+ }
+ }
+
+ private TypeAndName parseNameAndType(List<Expression> args, MethodCallExpression call, SourceUnit source,
+ String callName, boolean requireValidIdentifier) {
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ if (args.size() == 2 && args.get(0) instanceof ClassExpression) {
+ addError(call, source, callName + "(...) takes the name before the type: " +
Review Comment:
Fixed in `a4deb3d2cd`. `bean(String) { 'hi' }.lazy()` now reports
```
the body closure comes last, after every chained qualifier - write bean(...).lazy(...) { ... }
rather than bean(...) { ... }.lazy(...)
```
Put on the shared statement path rather than in `bean(...)`, so `field(...)` and `method(...)` get it too — `method('x', String) { 'y' }.annotate(...)` was landing on "must end with a body closure" the same way. Three table rows.
##########
grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy:
##########
@@ -22,16 +22,25 @@ package grails.plugin.cache
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
-import org.springframework.beans.factory.BeanRegistrar
-import org.springframework.beans.factory.BeanRegistry
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty
import org.springframework.cache.Cache
-import org.springframework.core.env.Environment
import grails.plugins.Plugin
import org.grails.plugin.cache.GrailsCacheManager
+/**
+ * Configures the cache plugin.
+ *
+ * <p>Every bean is contributed as auto-configuration so that one supplied by the application or
+ * another plugin — for example a cache-provider plugin's {@code grailsCacheManager} — makes the
+ * default back off cleanly instead of triggering a bean-definition override. The whole set is gated
+ * on {@code grails.cache.enabled}.</p>
+ */
@Slf4j
@CompileStatic
+@AutoConfiguration
+@ConditionalOnBooleanProperty(name = 'grails.cache.enabled', matchIfMissing = true)
Review Comment:
Deliberate, and now stated in the class javadoc (`33c9ee771d`) rather than left to omission: the jar being present is sufficient, as for an ordinary Boot starter. The gate cannot be restated once `grailsCacheConfiguration` is declared in this same block — it would condition on a bean the class contributes — and the plugin declares no `profiles` or `environments`, so it is active wherever its jar is. That is what makes it a change of mechanism rather than of which applications get the beans. The javadoc says a descriptor that later becomes conditionally inactive needs a new anchor.
On the property: real, but the direction is the other way round. Comparing `@ConditionalOnBooleanProperty` against `config.getProperty(..., Boolean, true)`:
| value | condition | old conversion |
| --- | --- | --- |
| `no` / `off` / `0` | disabled | disabled |
| `yes` / `on` / `1` | **disabled** | **enabled** |
So `=no` is unchanged; `=yes` is the regression. And it was worse than a disagreement: `doWithApplicationContext` re-read the flag with the relaxed conversion, so on `=yes` it believed caching was on and asked for `grailsCacheConfiguration` — which the condition had just declined to register. Startup failure.
That hook is now keyed on `applicationContext.containsBean(...)`, which cannot drift from the condition that decided it. The `log.warn` is restored with it.
##########
grails-beans-dsl/src/main/java/grails/compiler/beans/GrailsBeans.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.compiler.beans;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+
+/**
+ * Marks a class whose {@code beans} closure property is a bean-definition DSL that should be
+ * compiled into real {@code @Bean} factory methods, so the class can serve as a plain
+ * {@code @AutoConfiguration} with no closure DSL surviving into the compiled bytecode.
+ *
+ * <p>The annotated class must declare a {@code beans} property initialised to a closure whose
+ * statements are one of:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }} - or {@code bean(["name", ] Type)} with no body at all,
+ * which declares a bean that is simply {@code new Type()}, the most common shape. A closure with
+ * parameters but an empty body means the same for a bean with dependencies: the parameters say what
+ * is injected and the constructor call is generated from them, in the order written, leaving the
+ * compiler to select the constructor from their types just as it would for a hand-written body. Both
+ * forms require a concrete type; an interface or abstract type needs a body naming the
+ * implementation. It chains with the qualifiers below exactly as the
+ * closure form does ({@code bean(Foo).lazy().conditionalOnMissingBean()}). The closure form may be
+ * chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, the annotation's own named
+ * attributes such as {@code name:}/{@code search:}, or no arguments at all to let Spring infer
+ * the back-off type from the return type), {@code .conditionalOnMissingBeanName(...)} (backs off
+ * by this bean's own name - set automatically, stated once - accepting the annotation's other
+ * attributes but rejecting {@code name:} and types), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a {@code static} factory method - Spring's
+ * recommended shape for {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans, which
+ * must be creatable without instantiating their declaring configuration class), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])} - the last a generic escape hatch
+ * attaching any other single-valued annotation. The closure body becomes the generated method's
+ * body verbatim, and closure parameters become the generated method's parameters (for
+ * constructor-style bean injection). The generated method's name is an implementation detail:
+ * Spring resolves the bean by its {@code @Bean("name")} value, so a bean name that isn't a valid
+ * Java identifier (e.g. {@code "my-service"}) simply gets a synthesized {@code <type>$N} method
+ * name behind the scenes. The same bean name may even be declared by more than one
+ * {@code bean(...)} statement - the standard Spring Boot pattern for mutually exclusive variants
+ * of one bean - provided every declaration with the name carries its own discriminating
+ * condition (e.g. {@code .annotate(ConditionalOnProperty, ...)}) so that at most one of them
+ * registers at runtime.</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} and/or
+ * (repeatably) {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on
+ * the generated class, for state shared across bean methods. The usual case is injected
+ * configuration: {@code field("encoding", String).value(Settings.GSP_VIEW_ENCODING, "UTF-8")}
+ * compiles to {@code @Value("${grails.views.gsp.encoding:UTF-8}")} - the two-argument form takes
+ * a config key (a literal or a bare constant reference) plus default. The one-argument form
+ * takes a bare config key with no default ({@code .value("app.encoding")} compiles to
+ * {@code @Value("${app.encoding}")}), while a string already containing a {@code ${...}}
+ * placeholder or {@code #{...}} SpEL expression passes through verbatim.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ * When no name is given, one is derived from the type name following the JavaBeans convention
+ * ({@link java.beans.Introspector#decapitalize(String)}).
+ *
+ * <p>The generated methods work on any class Spring processes as a configuration source: a
+ * registered {@code @AutoConfiguration} or {@code @Configuration} class, or the Spring Boot
+ * application class itself (e.g. a Grails {@code Application} class) - Spring Boot reads
+ * {@code @Bean} methods directly off the class it is launched with, so no further registration
+ * is needed there.
+ *
+ * <p>May also be applied to a {@code grails.plugins.Plugin} subclass, letting bean definitions
+ * live in the familiar {@code *GrailsPlugin.groovy} file. In that case the generated methods land
+ * on a new sibling class instead, named by the plugin-descriptor convention - a {@code *GrailsPlugin}
+ * name swaps that suffix for {@code AutoConfiguration} ({@code I18nGrailsPlugin} ->
+ * {@code I18nAutoConfiguration}), any other name appends it - or {@link #autoConfigurationName}
+ * if given. A {@code Plugin} subclass is never processed by
+ * Spring as a bean, so {@code @AutoConfiguration} together with every annotation that gates or
+ * configures it (the {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources},
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - including any composed annotation
+ * meta-annotated with one of these) found on the plugin class moves onto that sibling, since none
+ * of them has any effect where the author wrote them. Annotations outside that set can be moved
+ * explicitly via {@link #moveAnnotations}.
+ */
+@Retention(RetentionPolicy.RUNTIME)
Review Comment:
Changed to `CLASS` in `4e51a2556a`, with a comment on the annotation recording why.
Nothing reads it: every converted module passes with it invisible, and `ExampleBeans` — which declares it explicitly — reports only `@AutoConfiguration` at runtime. It is a new annotation on an unreleased branch, so there is no compatibility cost, and your point about `grails-core` declaring the module `api` is what tipped it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5088823783
## ✅ All tests passed ✅
🏷️ Commit: 100b9dbf77d65a32cef2f1698113052fa9f59ac7
▶️ Tests: 65770 executed
⚪️ Checks: 61/61 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3686893207
##########
grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy:
##########
@@ -22,16 +22,25 @@ package grails.plugin.cache
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
-import org.springframework.beans.factory.BeanRegistrar
-import org.springframework.beans.factory.BeanRegistry
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty
import org.springframework.cache.Cache
-import org.springframework.core.env.Environment
import grails.plugins.Plugin
import org.grails.plugin.cache.GrailsCacheManager
+/**
+ * Configures the cache plugin.
+ *
+ * <p>Every bean is contributed as auto-configuration so that one supplied by the application or
+ * another plugin — for example a cache-provider plugin's {@code grailsCacheManager} — makes the
+ * default back off cleanly instead of triggering a bean-definition override. The whole set is gated
+ * on {@code grails.cache.enabled}.</p>
+ */
@Slf4j
@CompileStatic
+@AutoConfiguration
+@ConditionalOnBooleanProperty(name = 'grails.cache.enabled', matchIfMissing = true)
Review Comment:
Deliberate, and now stated in the class javadoc (`33c9ee771d`) rather than left to omission: the jar being present is sufficient, as for an ordinary Boot starter. The gate cannot be restated once `grailsCacheConfiguration` is declared in this same block — it would condition on a bean the class contributes — and the plugin declares no `profiles` or `environments`, so it is active wherever its jar is. That is what makes it a change of mechanism rather than of which applications get the beans. The javadoc says a descriptor that later becomes conditionally inactive needs a new anchor.
On the property: real, but the direction is the other way round. Comparing `@ConditionalOnBooleanProperty` against `config.getProperty(..., Boolean, true)`:
| value | condition | old conversion |
| --- | --- | --- |
| `no` / `off` / `0` | disabled | disabled |
| `yes` / `on` / `1` | **disabled** | **enabled** |
So `=no` is unchanged; `=yes` is the regression. And it was worse than a disagreement: `doWithApplicationContext` re-read the flag with the relaxed conversion, so on `=yes` it believed caching was on and asked for `grailsCacheConfiguration` — which the condition had just declined to register. Startup failure.
That hook is now keyed on `applicationContext.containsBean(...)`, which cannot drift from the condition that decided it. The `log.warn` is restored with it.
Covered in `9f18a77067`: three unrolled cases for `yes`/`on`/`1` asserting the beans are absent and the hook backs off. Against the previous implementation all three fail with `NoSuchBeanDefinitionException`, and a fourth case runs the hook on the enabled context so the back-off cannot pass by being taken unconditionally.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5127213481
## ✅ All tests passed ✅
🏷️ Commit: 9f0b4d5f7b1a263083ba34b63aa08fa1d64a976b
▶️ Tests: 61728 executed
⚪️ Checks: 62/62 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole merged PR #16019:
URL: https://github.com/apache/grails-core/pull/16019
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5095501387
The `grails-databinding` conversion (623ce9748d), which drove a DSL addition: `bean(Type)` no longer requires a factory closure (4dab384019). Five of these seven beans were nothing but their own no-argument construction, and spelling that out as `bean('xmlDataBindingSourceCreator', XmlDataBindingSourceCreator) { new XmlDataBindingSourceCreator() }` restates the type three times to say nothing. Imports and comments are trimmed here; each linked filename is the verbatim, commit-pinned source.
Before, [`DataBindingConfiguration.java`](https://github.com/codeconsole/grails-core/blob/700cf9c329a16e67179566a3879aeb29c3d7beb1/grails-databinding/src/main/groovy/org/grails/plugins/databinding/DataBindingConfiguration.java#L49-L132) (since deleted):
```java
@AutoConfiguration
@AutoConfigureOrder
@EnableConfigurationProperties(DataBindingConfigurationProperties.class)
@ImportAutoConfiguration(DefaultConvertersConfiguration.class)
public class DataBindingConfiguration {
private final DataBindingConfigurationProperties configurationProperties;
public DataBindingConfiguration(DataBindingConfigurationProperties configurationProperties) {
this.configurationProperties = configurationProperties;
}
@Lazy
@Bean("grailsWebDataBinder")
protected GrailsWebDataBinder grailsWebDataBinder(
GrailsApplication grailsApplication,
ValueConverter[] valueConverters,
FormattedValueConverter[] formattedValueConverters,
TypedStructuredBindingEditor[] structuredBindingEditors,
DataBindingListener[] dataBindingListeners) {
GrailsWebDataBinder dataBinder = new GrailsWebDataBinder(grailsApplication);
dataBinder.setConvertEmptyStringsToNull(configurationProperties.isConvertEmptyStringsToNull());
// ... converter/editor/listener merging with the main context, elided ...
return dataBinder;
}
@Bean("xmlDataBindingSourceCreator")
protected XmlDataBindingSourceCreator xmlDataBindingSourceCreator() {
return new XmlDataBindingSourceCreator();
}
@Bean("jsonDataBindingSourceCreator")
protected JsonDataBindingSourceCreator jsonDataBindingSourceCreator() {
return new JsonDataBindingSourceCreator();
}
@Bean("halJsonDataBindingSourceCreator")
protected HalJsonDataBindingSourceCreator halJsonDataBindingSourceCreator() {
return new HalJsonDataBindingSourceCreator();
}
@Bean("halXmlDataBindingSourceCreator")
protected HalXmlDataBindingSourceCreator halXmlDataBindingSourceCreator() {
return new HalXmlDataBindingSourceCreator();
}
@Bean("jsonApiDataBindingSourceCreator")
protected JsonApiDataBindingSourceCreator jsonApiDataBindingSourceCreator() {
return new JsonApiDataBindingSourceCreator();
}
@Bean("dataBindingSourceRegistry")
protected DataBindingSourceRegistry dataBindingSourceRegistry(DataBindingSourceCreator... creators) {
final DefaultDataBindingSourceRegistry registry = new DefaultDataBindingSourceRegistry();
registry.setDataBindingSourceCreators(creators);
registry.initialize();
return registry;
}
}
```
After — [`DataBindingGrailsPlugin.groovy`](https://github.com/codeconsole/grails-core/blob/bab7b058f3527c311c6da2464a72fdaab269c185/grails-databinding/src/main/groovy/org/grails/plugins/databinding/DataBindingGrailsPlugin.groovy#L60-L130)'s class declaration and `beans` block. The plugin previously held nothing but a `version` property, so this is the whole file:
```groovy
@CompileStatic
@GrailsBeans
@AutoConfiguration
@AutoConfigureOrder
@EnableConfigurationProperties(DataBindingConfigurationProperties)
@ImportAutoConfiguration(DefaultConvertersConfiguration)
class DataBindingGrailsPlugin extends Plugin {
def version = GrailsUtil.getGrailsVersion()
def beans = {
bean(GrailsWebDataBinder).lazy() { GrailsApplication grailsApplication,
DataBindingConfigurationProperties configurationProperties,
ValueConverter[] valueConverters,
FormattedValueConverter[] formattedValueConverters,
TypedStructuredBindingEditor[] structuredBindingEditors,
DataBindingListener[] dataBindingListeners ->
GrailsWebDataBinder dataBinder = new GrailsWebDataBinder(grailsApplication)
dataBinder.convertEmptyStringsToNull = configurationProperties.convertEmptyStringsToNull
// ... converter/editor/listener merging with the main context, elided ...
dataBinder
}
bean(XmlDataBindingSourceCreator)
bean(JsonDataBindingSourceCreator)
bean(HalJsonDataBindingSourceCreator)
bean(HalXmlDataBindingSourceCreator)
bean(JsonApiDataBindingSourceCreator)
bean(DataBindingSourceRegistry) { DataBindingSourceCreator[] creators ->
DefaultDataBindingSourceRegistry registry = new DefaultDataBindingSourceRegistry()
registry.dataBindingSourceCreators = creators
registry.initialize()
registry
}
}
}
```
**The bodyless `bean(Type)` form.** The trailing closure is now optional: `bean(Type)` and `bean('name', Type)` generate a parameterless factory method returning `new Type()`, and chain the existing qualifiers exactly as the closure form does — `bean(Widget).primary().lazy().conditionalOnMissingBean()` compiles the same way it would with an empty body. Because it constructs the *declared* type, it is rejected at compile time for an interface or abstract class with a message pointing at the fix, rather than deferring to a confusing error inside generated code. That is precisely why `dataBindingSourceRegistry` above keeps its closure: it declares the `DataBindingSourceRegistry` interface while constructing `DefaultDataBindingSourceRegistry` and then initializing it.
**No explicit names.** Each of these seven types decapitalizes to exactly the bean name the hand-written class declared, so passing the name would only restate it. Reading the `@Bean` values back out of the bytecode confirms all seven are unchanged. The same cleanup was applied to the earlier `grails-core` and `grails-cache` conversions (bab7b058f3), which had carried the same redundancy; the names that remain across all conversions are the ones a type genuinely does not produce — `grailsUrlConverter` from `UrlConverter`, `mailSession` from `JndiObjectFactoryBean`, `grailsDomainClassMappingContext` from `DefaultMappingContextFactoryBean`, and so on.
**Two structural notes.** `configurationProperties` was a constructor-injected field, and the generated sibling always has a no-arg constructor; only `grailsWebDataBinder` reads it, so that one bean takes it as a parameter. And `dataBindingSourceRegistry`'s `DataBindingSourceCreator...` parameter is written as an array — Spring resolves both identically, and javap shows Groovy hands the generated method the varargs flag back anyway, since a trailing array parameter on a closure compiles to varargs.
The class is renamed `DataBindingConfiguration` → `DataBindingAutoConfiguration` by the `*GrailsPlugin` → `*AutoConfiguration` convention. Beyond dropping the inconsistency, it corrects a class that was registered in `AutoConfiguration.imports` while named only `*Configuration`. The imports entry was its only reference in the repository; the 7.0 upgrade guide's note about the original `DataBindingGrailsPlugin` → `DataBindingConfiguration` move is left alone as an accurate record of the 7.x change.
One imperfection worth stating rather than glossing: the generated `grailsWebDataBinder` body keeps four explicit array casts on `GrailsArrayUtils.concat` that the Java original did not need. Groovy's `@CompileStatic` cannot infer `T[]` from `concat`'s `<T> T[]` signature the way javac does; removing the casts produces *more* runtime coercion, not less (nine `invokedynamic` sites rather than five), and an explicit type witness does not help either. The five that remain are all `invokedynamic cast` — array coercion, not dynamic dispatch — in a `@Lazy` bean method.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5094651012
The `grails-domain-class` conversion (700cf9c329), same pattern and the same naming decision as the cache one: the sibling takes the convention name `DomainClassAutoConfiguration` rather than being pinned to `GrailsDomainClassAutoConfiguration`. This one also exercises two things the earlier conversions did not — replacing constructor injection, and a rename that other modules reference. Imports and comments are trimmed here; each linked filename is the verbatim, commit-pinned source.
Before, [`GrailsDomainClassAutoConfiguration.groovy`](https://github.com/codeconsole/grails-core/blob/311fb9a959e646469432ba8983ee02319fffbd6c/grails-domain-class/src/main/groovy/org/grails/plugins/domain/GrailsDomainClassAutoConfiguration.groovy#L40-L79) (since deleted):
```groovy
@CompileStatic
@AutoConfiguration(afterName = ['org.grails.plugins.i18n.I18nAutoConfiguration'])
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
class GrailsDomainClassAutoConfiguration {
GrailsApplication grailsApplication
List<MessageSource> messageSources
@Autowired
GrailsDomainClassAutoConfiguration(GrailsApplication grailsApplication, List<MessageSource> messageSources) {
this.grailsApplication = grailsApplication
this.messageSources = messageSources
}
@Lazy
@Bean(name = 'grailsDomainClassMappingContext')
DefaultMappingContextFactoryBean grailsDomainClassMappingContext(List<ConstraintFactory> factories) {
new DefaultMappingContextFactoryBean(grailsApplication, messageSources).tap {
constraintFactories = factories ?: []
}
}
@Lazy
@Bean
DefaultConstraintEvaluatorFactoryBean validateableConstraintsEvaluator(@Qualifier('grailsDomainClassMappingContext') MappingContext mappingContext) {
new DefaultConstraintEvaluatorFactoryBean(messageSources, mappingContext, grailsApplication)
}
@Lazy
@Bean
ValidatorRegistryFactoryBean gormValidatorRegistry(@Qualifier('grailsDomainClassMappingContext') MappingContext mappingContext) {
new ValidatorRegistryFactoryBean().tap {
it.mappingContext = mappingContext
}
}
}
```
After — [`DomainClassGrailsPlugin.groovy`](https://github.com/codeconsole/grails-core/blob/700cf9c329a16e67179566a3879aeb29c3d7beb1/grails-domain-class/src/main/groovy/org/grails/plugins/domain/DomainClassGrailsPlugin.groovy#L49-L85)'s class declaration and `beans` block (the plugin's metadata properties between them are elided below, unchanged by the conversion; `beanRegistrar()` further down the file is pre-existing plugin logic, untouched):
```groovy
@CompileStatic
@GrailsBeans
@AutoConfiguration(afterName = ['org.grails.plugins.i18n.I18nAutoConfiguration'])
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
class DomainClassGrailsPlugin extends Plugin {
// ... pre-existing plugin metadata properties, unchanged ...
def beans = {
bean('grailsDomainClassMappingContext', DefaultMappingContextFactoryBean).lazy() { GrailsApplication grailsApplication, List<MessageSource> messageSources, List<ConstraintFactory> factories ->
new DefaultMappingContextFactoryBean(grailsApplication, messageSources).tap {
constraintFactories = factories ?: []
}
}
bean('validateableConstraintsEvaluator', DefaultConstraintEvaluatorFactoryBean).lazy() { GrailsApplication grailsApplication, List<MessageSource> messageSources, @Qualifier('grailsDomainClassMappingContext') MappingContext mappingContext ->
new DefaultConstraintEvaluatorFactoryBean(messageSources, mappingContext, grailsApplication)
}
bean('gormValidatorRegistry', ValidatorRegistryFactoryBean).lazy() { @Qualifier('grailsDomainClassMappingContext') MappingContext mappingContext ->
new ValidatorRegistryFactoryBean().tap {
it.mappingContext = mappingContext
}
}
}
```
The one structural change is the constructor. The deleted class held `grailsApplication` and `messageSources` as fields populated by an `@Autowired` constructor, and the generated sibling always has a no-arg constructor, so neither could be reproduced as-is. Declaring them as `field(...)` instead would not have worked either: a `field('messageSources', List)` is a raw `List`, and Spring cannot resolve that injection point without an element type. Taking both as bean method parameters keeps the generics, and Spring resolves them identically — only when the bean that needs them is created, rather than when the configuration class is instantiated. Verified with javap:
```
public DefaultMappingContextFactoryBean grailsDomainClassMappingContext(GrailsApplication, List<MessageSource>, List<ConstraintFactory>)
```
`List<MessageSource>` and `List<ConstraintFactory>` survive as distinct injection points, and the two `@Qualifier('grailsDomainClassMappingContext') MappingContext` parameters carry their annotation through from the closure.
Unlike the cache rename, this class is referenced across modules, so two call sites move with it. `ControllersAutoConfiguration` orders itself after this one by class literal, and that reference simply follows the rename — worth stating explicitly, since the generated sibling is emitted into the module's jar and therefore resolves from a dependent module's Java compile like any other class. (Verified rather than assumed: swapping the reference to `after = {DomainClassAutoConfiguration.class}` compiles cleanly.) That keeps the reference type-safe, so a future rename is a compile error rather than a silently stale string. The 8.0 upgrade guide's `grails-domain-class` row also gains a note naming the new class and telling anyone with an `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry to update it; the row's existing mention of the old name is left alone, since it documents the removed `constraintsEvaluator` API rather than the current class.
`grails-domain-class`, `grails-controllers`, `grails-cache` and the uber, web and persistence test suites all pass.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3684785698
##########
grails-doc/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc:
##########
@@ -119,6 +119,148 @@ class I18nGrailsPlugin extends Plugin {
A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.
+==== Compiling Bean Definitions into a Spring Boot AutoConfiguration
+
+
+`beanRegistrar()` and `doWithSpring` register beans at a single, fixed point in startup: before Spring Boot processes any `{springbootapi}org/springframework/boot/autoconfigure/AutoConfiguration.html[AutoConfiguration]`. That is enough for a bean to win against a Boot default guarded by `@ConditionalOnMissingBean`, but it cannot express ordering *relative to a specific* auto-configuration — running before `WebMvcAutoConfiguration` but after `MessageSourceAutoConfiguration`, say, regardless of where those two land in Boot's overall sort. Only a real `AutoConfiguration` class can declare that ordering, via `@AutoConfiguration(before = ..., after = ...)`.
+
+The link:{api}grails/compiler/beans/GrailsBeans.html[GrailsBeans] annotation lets you author bean definitions with DSL syntax similar to the classic Beans DSL, while compiling them at build time into genuine `@Bean` factory methods on a plain `AutoConfiguration` class — no closures, and nothing DSL-specific, survive into the compiled bytecode. Declare a class whose `beans` property is a closure of `bean(["name", ] Type) { ... }` statements:
+
+NOTE: On a `*GrailsPlugin.groovy` plugin descriptor or an application's `Application` class the annotation is implicit — a `beans` property is compiled automatically, the same way `doWithSpring` and `watchedResources` are conventions rather than annotated members. `@GrailsBeans` is written out only on a standalone class, as in the first example below. A class with no `beans` property is untouched.
+
+[source,groovy]
+----
+import grails.compiler.beans.GrailsBeans
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration
+import org.springframework.context.MessageSource
+import org.springframework.context.support.ReloadableResourceBundleMessageSource
+import org.springframework.web.servlet.i18n.CookieLocaleResolver
+import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
+
+@GrailsBeans
+@AutoConfiguration(before = [MessageSourceAutoConfiguration, WebMvcAutoConfiguration])
+class I18nBeans {
+
+ def beans = {
+ bean('messageSource', ReloadableResourceBundleMessageSource) {
+ new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
+ }
+
+ bean('localeResolver', CookieLocaleResolver).conditionalOnMissingBean(CookieLocaleResolver) {
+ new CookieLocaleResolver('locale')
+ }
+
+ bean('localeChangeInterceptor', LocaleChangeInterceptor) { MessageSource messageSource ->
+ new LocaleChangeInterceptor(paramName: 'lang')
+ }
+ }
+}
+----
+
+Each `bean(["name", ] Type)` statement compiles to a public method returning the declared type and annotated `@Bean("name")`. The generated method's name is an implementation detail — Spring resolves the bean by its `@Bean("name")` value, never by the method name. It matches the bean name when that is a valid Java identifier not already taken by an existing member (declared, inherited, or defined elsewhere in the DSL — a bean named `toString` will not override `Object.toString()`); otherwise a synthesized `<type>$N` name (`service$0`, `service$1`, ...) is used instead, so any legal, non-blank Spring bean name compiles:
+
+* The bean name defaults to the decapitalized simple class name when omitted.
+* The factory closure itself may be omitted when a bean is nothing but its own no-argument construction: `bean(XmlDataBindingSourceCreator)` declares exactly what `bean(XmlDataBindingSourceCreator) { new XmlDataBindingSourceCreator() }` does, without restating the type twice. It takes an explicit name (`bean('xmlCreator', XmlDataBindingSourceCreator)`) and chains the qualifiers below just as the closure form does (`bean(Widget).primary().lazy()`). The declared type is the one constructed, so it must be concrete and have an accessible no-argument constructor; for an interface or abstract type, give the bean a body naming the implementation.
+* Leaving the closure's *body* empty means the same thing for a bean with dependencies: the parameters say what is injected, and the constructor call is generated. `bean('validateableConstraintsEvaluator', DefaultConstraintEvaluatorFactoryBean).lazy() { List<MessageSource> messageSources, @Qualifier('grailsDomainClassMappingContext') MappingContext mappingContext, GrailsApplication grailsApplication -> }` generates a method with exactly those three parameters whose body is `new DefaultConstraintEvaluatorFactoryBean(messageSources, mappingContext, grailsApplication)` — the parameters in the order written. Which constructor that selects is decided by the compiler from the parameter types, exactly as for a body you wrote yourself, so nothing here depends on the declared type's other constructors. A body is still needed whenever construction is more than passing the parameters straight through — `new ConfigProperties(grailsApplication.config)`, or anything followed by `.tap { }`.
+* The same bean name may be declared by more than one `bean(...)` statement — the standard Spring Boot pattern for mutually exclusive variants of one bean, such as the framework's own `grailsUrlConverter` selected by `@ConditionalOnProperty` — provided every declaration with the name carries its own discriminating condition (such as `.annotate(ConditionalOnProperty, ...)`), so that at most one of them registers at runtime. Duplicating a bean name without that is a compile-time error, since Spring would keep the first definition and silently skip the rest.
+* Chaining `.conditionalOnMissingBean(...)` adds a `@ConditionalOnMissingBean` annotation to the generated method, matching Spring Boot's usual back-off semantics. It takes positional types (`.conditionalOnMissingBean(Greeter)`), the annotation's own named attributes (`.conditionalOnMissingBean(name: 'localeResolver', search: SearchStrategy.CURRENT)`), or both. With no arguments at all it compiles to the bare annotation, letting Spring Boot infer the back-off type from the method's return type — the recommended form when a bean simply backs off its own type, since `bean(AvailableLocaleResolver).conditionalOnMissingBean()` already says everything `.conditionalOnMissingBean(AvailableLocaleResolver)` would repeat.
+* Chaining `.conditionalOnMissingBeanName(...)` is the name-based counterpart: "register this bean unless a bean with *this bean's name* already exists". The condition's `name` member is set from the bean's own (explicit or convention-derived) name, so `bean(MessageSource).conditionalOnMissingBeanName(search: SearchStrategy.CURRENT) { ... }` states `messageSource` once and it feeds both `@Bean` and the condition — the two strings the explicit form has to keep in sync cannot diverge. It accepts the annotation's other attributes (`search:`, `ignored:`, ...) but rejects `name:` and types, which would contradict its purpose; use `.conditionalOnMissingBean(...)` for those.
+* Chaining `.primary()`, `.lazy()`, and/or `.scope("name")` adds `@Primary`, `@Lazy`, and `@Scope("name")` respectively.
+* Chaining `.staticMethod()` makes the generated factory method `static` — Spring's recommended shape for `BeanFactoryPostProcessor` and `BeanPostProcessor` beans, which must be creatable without instantiating their declaring configuration class. A static bean's closure cannot reference `field(...)` or `method(...)` members, since those are instance members; under `@CompileStatic` that mistake is a compile error.
+* Chaining `.annotate(AnnotationType[, attr: value, ...])` attaches any other single-valued annotation directly — any `@Conditional*` (built-in or a custom `Condition`), `@Order`, `@DependsOn`, or anything else a hand-written `@Bean` method could carry. It's repeatable, so several different annotations can be chained onto the same bean: `bean('special', Special).annotate(Order, value: 1).annotate(ConditionalOnProperty, prefix: 'myapp', name: 'enabled', havingValue: 'true') { ... }`.
+* Any combination of the above can be chained together, in any order — for example `bean('slowGreeter', SlowGreeter).lazy().scope('prototype') { ... }`.
+* Typed closure parameters (`{ MessageSource messageSource -> ... }`) become the generated method's parameters, so other beans are injected the same way a hand-written `@Bean` method would declare them — and a parameter-level annotation such as `{ @Qualifier('special') Greeter g -> ... }` carries straight through too, since the closure's own parameters become the generated method's parameters directly.
+
+Two more statement kinds can appear inside `beans { }` alongside `bean(...)`, for state and logic shared across bean methods — the same role a hand-written `@Configuration` class's own fields and private methods play:
+
+* `field(["name", ] Type)`, optionally chained with `.value(...)` and/or (repeatably) `.annotate(AnnotationType[, attr: value, ...])`, declares a private field on the generated class. The usual case is injected configuration, and `.value(...)` covers it directly: `field('encoding', String).value('grails.views.gsp.encoding', 'UTF-8')` compiles to `@Value("${grails.views.gsp.encoding:UTF-8}")`. The two-argument form takes a config key and default — and because the DSL builds the placeholder itself, the key may be a bare constant reference (`.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')`), the one shape a directly-written annotation value can't accept. The one-argument form takes a bare config key with no default — `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` — while a string already containing a `${...}` placeholder or a `#{...}` SpEL expression passes through verbatim: `.value('#{T(java.lang.Runtime).getRuntime().avail
ableProcessors()}')`.
+* `method(["name", ] Type) { ... }`, chainable with `.annotate(...)` only (`.value(...)` is field-specific), declares a private helper method the same way `bean(...)` declares a public one — typed closure parameters become method parameters, and the closure body becomes the method body.
+
+Both are ordinary private members of the generated class, so a `bean(...)` closure reads a `field(...)` or calls a `method(...)` exactly like a hand-written `@Bean` method would reference a sibling field or method on its own class:
+
+[source,groovy]
+----
+field('suffix', String).value('myapp.greeting-suffix', '!')
+
+method('buildGreeting', String) { String name ->
+ "Hello, ${name}${suffix}"
+}
+
+bean('greeting', Greeting) {
+ new Greeting(buildGreeting('World'))
+}
+----
+
+Because the result is an ordinary `AutoConfiguration` class, it must be registered the same way any Spring Boot auto-configuration is: listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`. Modules built as part of this project can apply the `org.apache.grails.buildsrc.autoconfiguration-imports` Gradle convention plugin to generate that file automatically, by scanning the module's own compiled classes for `@AutoConfiguration` at build time. Projects outside this build register the class the same way any hand-written `AutoConfiguration` is registered — by listing it in that file directly.
+
+NOTE: `@GrailsBeans` does not require extending `Plugin` at all — it produces a plain Spring Boot `AutoConfiguration`, so it can be used by any Spring Boot module, not just a Grails plugin descriptor. Applications can use it too, including directly on the `Application` class — where no imports-file registration is needed, since Spring Boot processes the application class itself — see link:spring.html#springdslAdditional[Configuring Additional Beans]. Within a plugin, reach for it specifically when a bean's registration needs to be ordered against a particular other auto-configuration; otherwise `beanRegistrar()` remains the recommended way to register beans from a `Plugin`.
+
+The DSL still covers a narrower surface than `doWithSpring(BeanBuilder)`:
+
+* Each top-level statement inside `beans { }` must be exactly `bean(...)`, `field(...)`, or `method(...)`, with their respective chaining — an `if`, a `for` loop, or any other imperative Groovy directly inside `beans { }` is a compile-time error, not a runtime one. Note that this is about the DSL's own top-level statements, not the bodies of `bean(...)`/`method(...)` closures themselves, which accept arbitrary Groovy, subject only to what is reachable from the generated class (see the last bullet below) — and `field(...)`/`method(...)` already cover the common reasons to want shared state or logic in the first place.
+* `.annotate(...)` attribute values must be compile-time constants: strings, numbers, booleans, class literals, enum constants, or arrays of these. A bare constant *reference* counts, and so does a *concatenation* of them — `.annotate(Value, value: '${' + Settings.I18N_LOCALE_RESOLVER + ':session}')` folds, `@CompileStatic` included, the same way `.value(...)` folds its arguments. The one shape that does not fold is a `static final` declared on a Groovy *class*: that is a property with a generated getter, and `@CompileStatic` rewrites the reference into a call to it. An interface's constants are real `public static final` fields and fold correctly — which is every `grails.config.Settings` key. An attribute that itself takes a nested annotation as its value isn't supported.
Review Comment:
The exception this bullet still carries is stale in the same way the concatenation one was, and for the same reason: `foldStringValue` resolves the value during canonicalization, before `@CompileStatic`'s transform runs, so there is no reference left for it to rewrite into a getter call.
A `static final` on a Groovy *class* does fold. All four combinations, with `@CompileStatic` on the annotated class:
| constant owner | `.value(KEY, 'x')` | `.annotate(Value, value: '${' + KEY + ':y}')` |
| --- | --- | --- |
| same-compilation-unit Groovy class | `${probe.key:x}` | `${probe.key:y}` |
| already-compiled Groovy class | `${precompiled.probe.key:x}` | `${precompiled.probe.key:y}` |
A bare reference as the whole attribute value folds too — `.annotate(Value, value: PrecompiledKeys.KEY)` gives `precompiled.probe.key`.
`findStaticFinalField` reads the `FieldNode`, and a Groovy property's backing field is still `static final` with its initial expression intact, so the property-versus-field distinction the bullet turns on no longer has any effect. As written it steers readers away from a shape that works — which is what the earlier version of this bullet did with `Settings`.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1354 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import groovy.transform.TypeChecked;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.GroovyBugError;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.ArgumentListExpression;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.expr.VariableExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.EmptyStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.ReturnStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.StaticTypesTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained. Its parameters are always the DSL closure's own, annotations
+ * included. Its body is the closure's, except where that body is empty - or the closure is omitted
+ * altogether - in which case a {@code new Type(...)} call over those same parameters is synthesised
+ * instead, leaving the compiler to select the constructor from their types exactly as it would for a
+ * body written out by hand. The generated method's name is an implementation detail: it matches the
+ * bean name when that is a usable Java identifier not already taken by an existing or generated
+ * member, and falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name
+ * like {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString}
+ * never overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ // An empty block is a no-op, not an error - an empty @Configuration class is legal in Spring
+ // and an empty resources.groovy is legal in Grails, so having nothing to declare should not
+ // fail the build. Returning before the sibling is created matters: generating it would leave
+ // a bean-less class holding the @AutoConfiguration and @Conditional* annotations moved off
+ // the plugin, which is worse than doing nothing. Only the DSL scaffolding is stripped.
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ if (statements.isEmpty()) {
+ removeBeansProperty(classNode, beansProperty);
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ removeBeansProperty(classNode, beansProperty);
+ }
+
+ private void removeBeansProperty(ClassNode classNode, PropertyNode beansProperty) {
+ classNode.getProperties().remove(beansProperty);
+ // removeField, not getFields().remove: the latter leaves ClassNode's own fieldIndex entry
+ // behind, so another member still referring to 'beans' type-checks and compiles to a
+ // getfield against a field that is never emitted, failing with NoSuchFieldError at runtime.
+ classNode.removeField(BEANS_PROPERTY);
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ // Without a position, anything Groovy later reports against a generated node - a sibling
+ // name clash, a typo in .annotate(...) - is reported at line -1, column -1.
+ sibling.setSourcePosition(pluginClass);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // The bean bodies are lifted onto a class the normal transform pipeline no longer visits, so
+ // whichever of these the author put on the plugin has to be re-applied here or the bodies are
+ // silently left unchecked. @GrailsCompileStatic and @GrailsTypeChecked need no handling of their
+ // own: @AnnotationCollector has already expanded them by canonicalization.
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ if (compilationUnit == null) {
+ return;
+ }
+ if (applyStaticTypesTransformation(pluginClass, sibling, source,
+ CompileStatic.class, new StaticCompileTransformation())) {
+ return;
+ }
+ applyStaticTypesTransformation(pluginClass, sibling, source,
+ TypeChecked.class, new StaticTypesTransformation());
+ }
+
+ private boolean applyStaticTypesTransformation(ClassNode pluginClass, ClassNode sibling, SourceUnit source,
+ Class<? extends java.lang.annotation.Annotation> annotationType, StaticTypesTransformation transformation) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(annotationType));
+ if (annotations.isEmpty()) {
+ return false;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(annotationType));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ siblingAnnotation.setSourcePosition(sourceAnnotation);
+ sibling.addAnnotation(siblingAnnotation);
+
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ return true;
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && discriminatesByType(args)) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ // @ConditionalOnMissingBean attributes that say nothing about a *type*. Where duplicates share
+ // one bean name - the only situation validateSharedBeanNames runs in - a name: or search: is
+ // identical on each of them and so can no more tell them apart than the bare form can.
+ private static final Set<String> NON_DISCRIMINATING_MISSING_BEAN_ATTRIBUTES = Set.of("name", "search");
+
+ private boolean discriminatesByType(List<Expression> args) {
+ boolean sawSomething = false;
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression) {
+ return true;
+ }
+ if (!(arg instanceof MapExpression)) {
+ // an argument shape this method does not model - stay lenient rather than reject
+ return true;
+ }
+ for (MapEntryExpression entry : ((MapExpression) arg).getMapEntryExpressions()) {
+ Object key = entry.getKeyExpression() instanceof ConstantExpression ?
+ ((ConstantExpression) entry.getKeyExpression()).getValue() : null;
+ if (!(key instanceof String) || !NON_DISCRIMINATING_MISSING_BEAN_ATTRIBUTES.contains(key)) {
+ return true;
+ }
+ sawSomething = true;
+ }
+ }
+ return !sawSomething && !args.isEmpty();
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ // The walk above stops at the first root call name it meets, so without this a root
+ // statement chained onto another - field("suffix", String).bean("greeter", String) { } -
+ // parses as one statement and the left-hand declaration is silently dropped.
+ if (!baseCall.isImplicitThis() && baseCall.getObjectExpression() instanceof MethodCallExpression) {
+ addError(statement, source, baseCall.getMethodAsString() + "(...) cannot be chained onto " +
+ ((MethodCallExpression) baseCall.getObjectExpression()).getMethodAsString() +
+ "(...) - each bean(...), field(...) and method(...) declaration is its own statement");
+ return;
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ // The factory closure is optional: bean(Type) with no body declares a bean that is just its
+ // own no-argument construction, which is by far the most common shape and reads as noise
+ // when spelled out as bean(Type) { new Type() }.
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ ClosureExpression factory = !closureCallArgs.isEmpty() &&
+ closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression ?
+ (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1) : null;
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (factory != null && baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ ClassNode beanType = typeAndName.type.getType();
+ // A closure whose body is empty declares construction too, from its own parameters: the
+ // parameters say what is injected, and the generated body is the constructor call the author
+ // would otherwise have written out. bean(Type) { } with no parameters is bean(Type).
+ boolean constructsDeclaredType = factory == null || isEmpty(factory.getCode());
+ if (constructsDeclaredType && (beanType.isInterface() || Modifier.isAbstract(beanType.getModifiers()))) {
+ addError(baseCall, source, "bean(" + beanType.getNameWithoutPackage() + ") with no factory closure body " +
+ "constructs the declared type, which cannot be done for an interface or abstract class - " +
+ "give it a body: bean(" + beanType.getNameWithoutPackage() + ") { new SomeImplementation() }");
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ Parameter[] beanParameters = factory == null || factory.getParameters() == null ?
+ Parameter.EMPTY_ARRAY : factory.getParameters();
+ Statement beanBody = constructsDeclaredType ?
Review Comment:
The synthesized `ConstructorCallExpression` is the one generated node in this file with no `setSourcePosition(...)`, and it is the node most likely to be the subject of a compile error: the constructor is selected from the closure's parameter types, so a parameter list matching no constructor — after someone adds an argument to the type's constructor, say — is the ordinary failure mode of the empty-body form.
Without a position the failure never reaches the error collector as a located message. Compiling the documented shape:
```groovy
class NeedsString {
NeedsString(String required) { }
}
@GrailsBeans
@CompileStatic
@AutoConfiguration
class ProbeWrongParams {
def beans = {
bean(NeedsString) { Integer n ->
}
}
}
```
In a normal build (assertions off):
```
org.codehaus.groovy.GroovyBugError: BUG! exception in phase 'class generation' in source unit '...' at line -1 column -1
On receiver: NeedsString with message: <$constructor$> and arguments: (n)
StaticTypesCallSiteWriter#makeCallSite should not have been called. Call site lacked method target for static compilation.
Please try to create a simple example reproducing this error and file a bug report at https://issues.apache.org/jira/browse/GROOVY
```
Under `-ea` — which is what Gradle's test workers run with, so it is what a plugin author sees from `./gradlew test` — it degrades further, to a bare `java.lang.AssertionError: null` out of `StaticCompilationVisitor.visitConstructorCallExpression`. The bodyless `bean(NeedsString)` spelling fails identically. Same failure class as the `getTypeClass()` one: an internal compiler error at line -1 in place of a located message, with an invitation to file a Groovy bug.
The discrepancy is that the hand-written equivalent this is documented as compiling to is diagnosed properly:
```
[Static type checking] - Cannot find matching constructor NeedsArgsHand(). Please check if the declared type is correct and if the method exists.
@ line 15, column 43.
bean(NeedsArgsHand) { new NeedsArgsHand() }
^
```
So "resolved from these argument types exactly as it would be for a hand-written `new Type(...)`" holds for resolution but not for what the author is told when it fails.
Copying the position onto the construction closes it. Verified against the branch:
```java
ConstructorCallExpression construction =
new ConstructorCallExpression(beanType, constructorArguments(beanParameters));
construction.setSourcePosition(baseCall);
```
after which the same fixture reports
```
[Static type checking] - Cannot find matching constructor NeedsString(java.lang.Integer). Please check if the declared type is correct and if the method exists.
@ line 15, column 21.
bean(NeedsString) { Integer n ->
^
```
pointing at the `bean(...)` statement. A test would help: the spec has no case for a constructor mismatch in either the bodyless or the empty-body form, which is why this got through.
##########
grails-doc/src/en/guide/upgrading/upgrading80x.adoc:
##########
@@ -1600,7 +1600,19 @@ This was introduced during the Grails 7.1 plugin-loading changes and remains req
| `grails-domain-class`
| `ConstraintEvaluatorAdapter` and `GrailsDomainClassAutoConfiguration.constraintsEvaluator(...)`
-| Code that imported the auto-configuration method should use the current `validateableConstraintsEvaluator(...)` bean path and the datastore constraint evaluator APIs.
+| Code that imported the auto-configuration method should use the current `validateableConstraintsEvaluator(...)` bean path and the datastore constraint evaluator APIs. The auto-configuration itself is now named `org.grails.plugins.domain.DomainClassAutoConfiguration`, following the `*GrailsPlugin` -> `*AutoConfiguration` convention; update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name.
+
+| `grails-core`
+| `org.grails.plugins.core.CoreAutoConfiguration`
+| Now `org.grails.plugins.CoreAutoConfiguration`. The class is generated beside the plugin descriptor that declares its beans, and `CoreGrailsPlugin` lives in `org.grails.plugins`, so the simple name is unchanged but the package is not. Update any `@EnableAutoConfiguration(exclude = ...)`, `spring.autoconfigure.exclude`, or `@AutoConfigureAfter(name = ...)` entry naming the old package. Spring Boot only reports an invalid exclude for a class still on the classpath, so a stale entry is silently ignored rather than reported, and the beans it was meant to suppress are registered anyway.
+
+| `grails-cache`
+| `grails.plugin.cache.GrailsCacheAutoConfiguration`
+| Now `grails.plugin.cache.CacheAutoConfiguration`, following the `*GrailsPlugin` -> `*AutoConfiguration` convention. Update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name; the same silent-ignore applies as above.
+
+| `grails-databinding`
+| `org.grails.plugins.databinding.DataBindingConfiguration`
+| Now `org.grails.plugins.databinding.DataBindingAutoConfiguration`. It was registered as an auto-configuration while named only `*Configuration`; the name now says what it is. Update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name; the same silent-ignore applies as above.
Review Comment:
These four rows cover every FQCN change, but not the one change in this PR that alters which beans a running application ends up with.
The component-scan fix means an application whose working directory is not the project root — a systemd unit, a container with its own `WORKDIR`, an app server — starts registering `@Component`s under `grails.spring.bean.packages` that it silently did not register before. The PR description says so plainly ("Applications that deploy this way will start getting beans they currently miss"); the guide says nothing.
It arguably deserves a row here more than the renames do. A stale exclude entry leaves a name that no longer resolves, which someone can at least search for; this one changes the contents of a running context with nothing to grep for, and in the direction of *adding* beans — a duplicate registration or an unexpected `@Component` picking up a bean name is how it will present.
Worth noting while you are here that `grails.spring.bean.packages` appears nowhere in `grails-doc` at all, so there is no existing page describing the property for this to cross-reference.
##########
grails-beans-dsl/src/main/java/grails/compiler/beans/GrailsBeans.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.compiler.beans;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+
+/**
+ * Marks a class whose {@code beans} closure property is a bean-definition DSL that should be
+ * compiled into real {@code @Bean} factory methods, so the class can serve as a plain
+ * {@code @AutoConfiguration} with no closure DSL surviving into the compiled bytecode.
+ *
+ * <p>The annotated class must declare a {@code beans} property initialised to a closure whose
+ * statements are one of:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }} - or {@code bean(["name", ] Type)} with no body at all,
+ * which declares a bean that is simply {@code new Type()}, the most common shape. A closure with
+ * parameters but an empty body means the same for a bean with dependencies: the parameters say what
+ * is injected and the constructor call is generated from them, in the order written, leaving the
+ * compiler to select the constructor from their types just as it would for a hand-written body. Both
+ * forms require a concrete type; an interface or abstract type needs a body naming the
+ * implementation. It chains with the qualifiers below exactly as the
+ * closure form does ({@code bean(Foo).lazy().conditionalOnMissingBean()}). The closure form may be
+ * chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, the annotation's own named
+ * attributes such as {@code name:}/{@code search:}, or no arguments at all to let Spring infer
+ * the back-off type from the return type), {@code .conditionalOnMissingBeanName(...)} (backs off
+ * by this bean's own name - set automatically, stated once - accepting the annotation's other
+ * attributes but rejecting {@code name:} and types), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a {@code static} factory method - Spring's
+ * recommended shape for {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans, which
+ * must be creatable without instantiating their declaring configuration class), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])} - the last a generic escape hatch
+ * attaching any other single-valued annotation. The closure body becomes the generated method's
+ * body verbatim, and closure parameters become the generated method's parameters (for
+ * constructor-style bean injection). The generated method's name is an implementation detail:
+ * Spring resolves the bean by its {@code @Bean("name")} value, so a bean name that isn't a valid
+ * Java identifier (e.g. {@code "my-service"}) simply gets a synthesized {@code <type>$N} method
+ * name behind the scenes. The same bean name may even be declared by more than one
+ * {@code bean(...)} statement - the standard Spring Boot pattern for mutually exclusive variants
+ * of one bean - provided every declaration with the name carries its own discriminating
+ * condition (e.g. {@code .annotate(ConditionalOnProperty, ...)}) so that at most one of them
+ * registers at runtime.</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} and/or
+ * (repeatably) {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on
+ * the generated class, for state shared across bean methods. The usual case is injected
+ * configuration: {@code field("encoding", String).value(Settings.GSP_VIEW_ENCODING, "UTF-8")}
+ * compiles to {@code @Value("${grails.views.gsp.encoding:UTF-8}")} - the two-argument form takes
+ * a config key (a literal or a bare constant reference) plus default. The one-argument form
+ * takes a bare config key with no default ({@code .value("app.encoding")} compiles to
+ * {@code @Value("${app.encoding}")}), while a string already containing a {@code ${...}}
+ * placeholder or {@code #{...}} SpEL expression passes through verbatim.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ * When no name is given, one is derived from the type name following the JavaBeans convention
+ * ({@link java.beans.Introspector#decapitalize(String)}).
+ *
+ * <p>The generated methods work on any class Spring processes as a configuration source: a
+ * registered {@code @AutoConfiguration} or {@code @Configuration} class, or the Spring Boot
+ * application class itself (e.g. a Grails {@code Application} class) - Spring Boot reads
+ * {@code @Bean} methods directly off the class it is launched with, so no further registration
+ * is needed there.
+ *
+ * <p>May also be applied to a {@code grails.plugins.Plugin} subclass, letting bean definitions
+ * live in the familiar {@code *GrailsPlugin.groovy} file. In that case the generated methods land
+ * on a new sibling class instead, named by the plugin-descriptor convention - a {@code *GrailsPlugin}
+ * name swaps that suffix for {@code AutoConfiguration} ({@code I18nGrailsPlugin} ->
+ * {@code I18nAutoConfiguration}), any other name appends it - or {@link #autoConfigurationName}
+ * if given. A {@code Plugin} subclass is never processed by
+ * Spring as a bean, so {@code @AutoConfiguration} together with every annotation that gates or
+ * configures it (the {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources},
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - including any composed annotation
+ * meta-annotated with one of these) found on the plugin class moves onto that sibling, since none
+ * of them has any effect where the author wrote them. Annotations outside that set can be moved
+ * explicitly via {@link #moveAnnotations}.
+ */
+@Retention(RetentionPolicy.RUNTIME)
Review Comment:
Carrying this forward from the scope thread so it does not get lost with it, since that thread's actual question — one story for the nine declarations — is settled.
Nothing reads `@GrailsBeans` at runtime. The transform consumes it at canonicalization, and it is not among the annotations moved to the generated sibling, so it stays on the source class where it is inert. `RetentionPolicy.CLASS` would leave every compile-time use working while keeping it out of the runtime image — which matters slightly more now that `grails-core` declares `grails-beans-dsl` as `api` and so puts it, and its own `spring-context`/`spring-boot-autoconfigure` `api` dependencies, on every application's runtime classpath.
Not a blocker, and I am fine with either answer. If `RUNTIME` is deliberate — leaving room for a runtime consumer later, say — a line on the annotation saying so is enough to close it.
##########
grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy:
##########
@@ -22,16 +22,25 @@ package grails.plugin.cache
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
-import org.springframework.beans.factory.BeanRegistrar
-import org.springframework.beans.factory.BeanRegistry
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty
import org.springframework.cache.Cache
-import org.springframework.core.env.Environment
import grails.plugins.Plugin
import org.grails.plugin.cache.GrailsCacheManager
+/**
+ * Configures the cache plugin.
+ *
+ * <p>Every bean is contributed as auto-configuration so that one supplied by the application or
+ * another plugin — for example a cache-provider plugin's {@code grailsCacheManager} — makes the
+ * default back off cleanly instead of triggering a bean-definition override. The whole set is gated
+ * on {@code grails.cache.enabled}.</p>
+ */
@Slf4j
@CompileStatic
+@AutoConfiguration
+@ConditionalOnBooleanProperty(name = 'grails.cache.enabled', matchIfMissing = true)
Review Comment:
`@ConditionalOnBean(CachePluginConfiguration)` came off in this conversion and nothing replaces it. The deleted `GrailsCacheAutoConfiguration` carried it with the reason spelled out:
> Gated on the `CachePluginConfiguration` definition contributed by the cache plugin descriptor's registrar (which runs before auto-configuration conditions are evaluated), so the auto-configuration backs off entirely when the plugin is not active — e.g. the jar is on the classpath but the plugin is excluded — keeping it in lockstep with the descriptor.
The gate could not survive verbatim: `grailsCacheConfiguration` is now declared in this same `beans` block rather than by the registrar, so it would be conditioning on a bean the same class contributes. But the condition it expressed has gone with it. With only `@ConditionalOnBooleanProperty(name = 'grails.cache.enabled')` left, a build with `grails-cache` on the classpath but the plugin not loaded now gets `grailsCacheConfiguration`, `grailsCacheAdminService`, `customCacheKeyGenerator` and `grailsCacheManager` registered anyway — exactly the case the deleted comment named.
Is that deliberate, i.e. is jar-on-the-classpath now sufficient for the cache beans, the way it is for an ordinary Boot starter? If so the class javadoc should say it: it explains the back-off design carefully but is silent on the lockstep that was dropped. If not, the descriptor no longer contributes anything for the generated configuration to gate on, so restoring it needs a different anchor — either way better decided explicitly than by omission.
Two smaller notes on the same move. `environment.getProperty('grails.cache.enabled', Boolean, true)` and `@ConditionalOnBooleanProperty` do not agree on non-canonical values: Spring's `Boolean` conversion accepts `yes`/`on`/`1`, the condition matches only `true`/`false`, so `grails.cache.enabled=no` used to disable the plugin and now leaves it enabled. And the `log.warn('Cache plugin is disabled')` that accompanied the old gate is gone, so disabling it is now silent.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1354 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import groovy.transform.TypeChecked;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.GroovyBugError;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.ArgumentListExpression;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.expr.VariableExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.EmptyStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.ReturnStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.StaticTypesTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained. Its parameters are always the DSL closure's own, annotations
+ * included. Its body is the closure's, except where that body is empty - or the closure is omitted
+ * altogether - in which case a {@code new Type(...)} call over those same parameters is synthesised
+ * instead, leaving the compiler to select the constructor from their types exactly as it would for a
+ * body written out by hand. The generated method's name is an implementation detail: it matches the
+ * bean name when that is a usable Java identifier not already taken by an existing or generated
+ * member, and falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name
+ * like {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString}
+ * never overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ // An empty block is a no-op, not an error - an empty @Configuration class is legal in Spring
+ // and an empty resources.groovy is legal in Grails, so having nothing to declare should not
+ // fail the build. Returning before the sibling is created matters: generating it would leave
+ // a bean-less class holding the @AutoConfiguration and @Conditional* annotations moved off
+ // the plugin, which is worse than doing nothing. Only the DSL scaffolding is stripped.
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ if (statements.isEmpty()) {
+ removeBeansProperty(classNode, beansProperty);
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ removeBeansProperty(classNode, beansProperty);
+ }
+
+ private void removeBeansProperty(ClassNode classNode, PropertyNode beansProperty) {
+ classNode.getProperties().remove(beansProperty);
+ // removeField, not getFields().remove: the latter leaves ClassNode's own fieldIndex entry
+ // behind, so another member still referring to 'beans' type-checks and compiles to a
+ // getfield against a field that is never emitted, failing with NoSuchFieldError at runtime.
+ classNode.removeField(BEANS_PROPERTY);
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ // Without a position, anything Groovy later reports against a generated node - a sibling
+ // name clash, a typo in .annotate(...) - is reported at line -1, column -1.
+ sibling.setSourcePosition(pluginClass);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // The bean bodies are lifted onto a class the normal transform pipeline no longer visits, so
+ // whichever of these the author put on the plugin has to be re-applied here or the bodies are
+ // silently left unchecked. @GrailsCompileStatic and @GrailsTypeChecked need no handling of their
+ // own: @AnnotationCollector has already expanded them by canonicalization.
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ if (compilationUnit == null) {
+ return;
+ }
+ if (applyStaticTypesTransformation(pluginClass, sibling, source,
+ CompileStatic.class, new StaticCompileTransformation())) {
+ return;
+ }
+ applyStaticTypesTransformation(pluginClass, sibling, source,
+ TypeChecked.class, new StaticTypesTransformation());
+ }
+
+ private boolean applyStaticTypesTransformation(ClassNode pluginClass, ClassNode sibling, SourceUnit source,
+ Class<? extends java.lang.annotation.Annotation> annotationType, StaticTypesTransformation transformation) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(annotationType));
+ if (annotations.isEmpty()) {
+ return false;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(annotationType));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ siblingAnnotation.setSourcePosition(sourceAnnotation);
+ sibling.addAnnotation(siblingAnnotation);
+
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ return true;
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && discriminatesByType(args)) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ // @ConditionalOnMissingBean attributes that say nothing about a *type*. Where duplicates share
+ // one bean name - the only situation validateSharedBeanNames runs in - a name: or search: is
+ // identical on each of them and so can no more tell them apart than the bare form can.
+ private static final Set<String> NON_DISCRIMINATING_MISSING_BEAN_ATTRIBUTES = Set.of("name", "search");
+
+ private boolean discriminatesByType(List<Expression> args) {
+ boolean sawSomething = false;
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression) {
+ return true;
+ }
+ if (!(arg instanceof MapExpression)) {
+ // an argument shape this method does not model - stay lenient rather than reject
+ return true;
+ }
+ for (MapEntryExpression entry : ((MapExpression) arg).getMapEntryExpressions()) {
+ Object key = entry.getKeyExpression() instanceof ConstantExpression ?
+ ((ConstantExpression) entry.getKeyExpression()).getValue() : null;
+ if (!(key instanceof String) || !NON_DISCRIMINATING_MISSING_BEAN_ATTRIBUTES.contains(key)) {
+ return true;
+ }
+ sawSomething = true;
+ }
+ }
+ return !sawSomething && !args.isEmpty();
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ // The walk above stops at the first root call name it meets, so without this a root
+ // statement chained onto another - field("suffix", String).bean("greeter", String) { } -
+ // parses as one statement and the left-hand declaration is silently dropped.
+ if (!baseCall.isImplicitThis() && baseCall.getObjectExpression() instanceof MethodCallExpression) {
+ addError(statement, source, baseCall.getMethodAsString() + "(...) cannot be chained onto " +
+ ((MethodCallExpression) baseCall.getObjectExpression()).getMethodAsString() +
+ "(...) - each bean(...), field(...) and method(...) declaration is its own statement");
+ return;
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ // The factory closure is optional: bean(Type) with no body declares a bean that is just its
+ // own no-argument construction, which is by far the most common shape and reads as noise
+ // when spelled out as bean(Type) { new Type() }.
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ ClosureExpression factory = !closureCallArgs.isEmpty() &&
+ closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression ?
+ (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1) : null;
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (factory != null && baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ ClassNode beanType = typeAndName.type.getType();
+ // A closure whose body is empty declares construction too, from its own parameters: the
+ // parameters say what is injected, and the generated body is the constructor call the author
+ // would otherwise have written out. bean(Type) { } with no parameters is bean(Type).
+ boolean constructsDeclaredType = factory == null || isEmpty(factory.getCode());
+ if (constructsDeclaredType && (beanType.isInterface() || Modifier.isAbstract(beanType.getModifiers()))) {
+ addError(baseCall, source, "bean(" + beanType.getNameWithoutPackage() + ") with no factory closure body " +
+ "constructs the declared type, which cannot be done for an interface or abstract class - " +
+ "give it a body: bean(" + beanType.getNameWithoutPackage() + ") { new SomeImplementation() }");
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ Parameter[] beanParameters = factory == null || factory.getParameters() == null ?
+ Parameter.EMPTY_ARRAY : factory.getParameters();
+ Statement beanBody = constructsDeclaredType ?
+ new ReturnStatement(new ConstructorCallExpression(beanType, constructorArguments(beanParameters))) :
+ factory.getCode();
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ beanType,
+ beanParameters,
+ ClassNode.EMPTY_ARRAY,
+ beanBody);
+ beanMethod.setSourcePosition(baseCall);
+ beanMethod.addAnnotation(withPosition(beanAnnotation(typeAndName.name), baseCall));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (factory != null && qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private boolean isEmpty(Statement code) {
+ return code == null || code instanceof EmptyStatement ||
+ (code instanceof BlockStatement && ((BlockStatement) code).getStatements().isEmpty());
+ }
+
+ /**
+ * The closure's parameters, passed straight through as the constructor's arguments. Which
+ * constructor that selects is left to the compiler, resolved from these argument types exactly as
+ * it would be for a hand-written {@code new Type(...)} - nothing here reads the declared type's
+ * constructors, so adding one cannot change what this bean injects.
+ */
+ private ArgumentListExpression constructorArguments(Parameter[] parameters) {
+ ArgumentListExpression arguments = new ArgumentListExpression();
+ for (Parameter parameter : parameters) {
+ arguments.addExpression(new VariableExpression(parameter));
+ }
+ return arguments;
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+ field.setSourcePosition(baseCall);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = findStaticFinalField(owner, fieldName, new HashSet<>());
+ if (field != null && field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ // The reflective fallback needs a loaded Class, which a ClassNode from this same
+ // compilation unit does not have - getTypeClass() would throw GroovyBugError, an
+ // AssertionError that no catch below would hold, aborting the compilation with an
+ // internal compiler error instead of the located message the caller reports.
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
+ return value instanceof String ? (String) value : null;
+ }
+ catch (ReflectiveOperationException | RuntimeException | LinkageError | GroovyBugError ignored) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ // ClassNode.getField walks superclasses but not interfaces, so a constant declared on an
+ // implemented interface - the shape every grails.config.Settings key has - is invisible to it
+ // while the owner is still being compiled.
+ private FieldNode findStaticFinalField(ClassNode owner, String fieldName, Set<String> visited) {
+ for (ClassNode type = owner; type != null; type = type.getSuperClass()) {
+ if (!visited.add(type.getName())) {
+ return null;
+ }
+ FieldNode declared = type.getDeclaredField(fieldName);
+ if (declared != null && declared.isStatic() && declared.isFinal()) {
+ return declared;
+ }
+ for (ClassNode implemented : type.getInterfaces()) {
+ FieldNode inherited = findStaticFinalField(implemented, fieldName, visited);
+ if (inherited != null) {
+ return inherited;
+ }
+ }
+ }
+ return null;
+ }
+
+ private void processMethodStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "method(...) must end with a body closure: method(\"name\", Type) { ... }");
+ return;
+ }
+ ClosureExpression body = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, METHOD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ MethodNode helperMethod = new MethodNode(
+ typeAndName.name,
+ Modifier.PRIVATE,
+ typeAndName.type.getType(),
+ body.getParameters() == null ? Parameter.EMPTY_ARRAY : body.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ body.getCode());
+ helperMethod.setSourcePosition(baseCall);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyGenericAnnotation(helperMethod, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(helperMethod);
+ }
+
+ private static final class TypeAndName {
+ private final ClassExpression type;
+ private final String name;
+
+ TypeAndName(ClassExpression type, String name) {
+ this.type = type;
+ this.name = name;
+ }
+ }
+
+ private TypeAndName parseNameAndType(List<Expression> args, MethodCallExpression call, SourceUnit source,
+ String callName, boolean requireValidIdentifier) {
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ if (args.size() == 2 && args.get(0) instanceof ClassExpression) {
+ addError(call, source, callName + "(...) takes the name before the type: " +
Review Comment:
This branch fires for a shape that has nothing to do with argument order, and the message then sends the reader somewhere unrelated. Chaining a qualifier *after* the factory closure rather than before it:
```groovy
bean(String) { 'hi' }.lazy()
```
```
bean(...) takes the name before the type: bean("myGreeter", Greeter), not bean(Greeter, "myGreeter")
@ line 9, column 34.
bean(String) { 'hi' }.lazy()
^
```
The named spelling avoids the wrong advice but is no more useful:
```groovy
bean('greeting', String) { 'hi' }.lazy()
```
```
bean(...) requires a type, optionally preceded by a name, e.g. bean(Greeter) or bean("myGreeter", Greeter)
```
It arrives here because `factory` is read off `outerCall`'s arguments, so a closure sitting on `baseCall` is never stripped and is still in `baseArgs` at this point. Both spellings are a plausible first guess: the closure reads as belonging to `bean(...)`, and it is where a body goes in every other DSL a Grails author writes. `method('name', Type) { ... }.annotate(X)` lands the same way, via "method(...) must end with a body closure".
Detecting a trailing `ClosureExpression` on the base call when qualifiers are present, and saying that qualifiers come before the body, is a one-line diagnostic — and a row in the malformed-statement table.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5137360638
## 🚨 TestLens detected 1 failed test 🚨
Here is what you can do:
1) Inspect the test failures carefully.
2) If you are convinced that some of the tests are flaky, you can mute them below.
3) Finally, trigger a rerun by checking the rerun checkbox.
### Test Summary
#### [CI / Functional Tests \(Java 21, indy\=true\)](https://github.com/apache/grails-core/actions/runs/30589181260/job/91027477751?pr=16019) > :grails-test-examples-app1:integrationTest
| Test | Runs | Flakiness |
|---|---|--:|
| RedirectWithAndWithoutParamsFunctionalSpec > Params are not added to the url after a redirect even if they are passed to the redirect | ❌ | [1% 🟡](https://github.com/apache/grails-core/issues/16030) |
🏷️ Commit: 7d90d67932d09b53f6996fa607d81e82b400e82b
▶️ Tests: 28594 executed
🟡 Checks: 24/56 completed
### Test Failures
<details>
<summary><strong>RedirectWithAndWithoutParamsFunctionalSpec > Params are not added to the url after a redirect even if they are passed to the redirect</strong> (:grails-test-examples-app1:integrationTest in <a href="https://github.com/apache/grails-core/actions/runs/30589181260/job/91027477751?pr=16019">CI / Functional Tests (Java 21, indy=true)</a>)</summary>
```
Condition not satisfied:
pageSource.contains('"id":')
| |
| false
<html><head></head><body><form action="save" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body></html>
at functionaltests.RedirectWithAndWithoutParamsFunctionalSpec.$tt__$spock_feature_1_0(RedirectWithAndWithoutParamsFunctionalSpec.groovy:41)
at functionaltests.RedirectWithAndWithoutParamsFunctionalSpec.Params are not added to the url after a redirect even if they are passed to the redirect_closure1(RedirectWithAndWithoutParamsFunctionalSpec.groovy)
at grails.gorm.transactions.GrailsTransactionTemplate$1.doInTransaction(GrailsTransactionTemplate.groovy:72)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:137)
at grails.gorm.transactions.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:69)
at functionaltests.RedirectWithAndWithoutParamsFunctionalSpec.Params are not added to the url after a redirect even if they are passed to the redirect(RedirectWithAndWithoutParamsFunctionalSpec.groovy)
```
</details>
### Muted Tests
> [!NOTE]
> Checks are currently running using the configuration below.
Select tests to mute in this pull request:
🔲 RedirectWithAndWithoutParamsFunctionalSpec > Params are not added to the url after a redirect even if they are passed to the redirect <!-- uniqueId=[engine:spock]/[spec:functionaltests.RedirectWithAndWithoutParamsFunctionalSpec]/[feature:$spock_feature_1_0] -->
Reuse successful test results:
🔲 ♻️ Only rerun the tests that failed or were muted before
Click the checkbox to trigger a rerun:
🔲 **Rerun jobs**
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3658540845
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
Review Comment:
Removing the backing field by mutating the list returned by `getFields()` leaves `ClassNode`'s internal `fieldIndex` entry behind — `removeField("beans")` is the API that clears both. With the stale index in place, another member of the annotated class that still references `beans` type-checks and compiles to a `getfield`, but nothing is emitted for it.
Confirmed against this branch — compiles clean, then dies at runtime:
```groovy
@GrailsBeans
@AutoConfiguration
class Fixture {
def beans = { bean('g', String) { 'hi' } }
def peek() { beans }
}
```
```
COMPILE: OK
java.lang.NoSuchFieldError: Class Fixture does not have member field 'java.lang.Object beans'
at Fixture.peek(...)
```
Same with `@CompileStatic`, with `this.@beans`, and in the `Plugin` form. Under `@CompileStatic` with an explicit return type it does surface at compile time, but as a misleading diagnostic that exposes the stale `Object`-typed entry rather than saying the property is gone:
```
[Static type checking] - Cannot return value of type java.lang.Object for method returning groovy.lang.Closure
```
The same call is made from the early-return path for an empty `beans` block, so both sites are affected.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
Review Comment:
The loop stops at the first name in `ROOT_STATEMENT_CALL_NAMES` walking inward, and never checks what the root call's own receiver is. So one root statement chained onto another parses as a single statement and the left-hand declaration is silently dropped:
```groovy
field('suffix', String).bean('greeter', String) { 'hi' }
```
That compiles cleanly, registers `greeter`, and never declares `suffix` — the failure only shows up at runtime. Every other unrecognised chain shape is a compile error here, so this one being accepted looks unintended. Worth rejecting when `baseCall.getObjectExpression()` is a `MethodCallExpression` (rather than the implicit-this receiver) and adding it to the `rejects a malformed beans statement` table.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
Review Comment:
This only matches `groovy.transform.CompileStatic`. `@TypeChecked` (and `@GrailsTypeChecked`) on the plugin class is therefore dropped, and the bean bodies lifted onto the generated sibling get no type checking at all — while the same DSL in the standalone form is checked, because there the members land on a class the normal transform pipeline still visits.
Silently downgrading to no checking is the surprising part. Either propagate `@TypeChecked` the same way, or reject it with a message saying it is not supported on a `Plugin` subclass.
(`@GrailsCompileStatic` is fine — `@AnnotationCollector` has already expanded it to a real `@CompileStatic` by canonicalization.)
##########
grails-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:
##########
@@ -1 +1 @@
-org.grails.plugins.core.CoreAutoConfiguration
\ No newline at end of file
+org.grails.plugins.CoreAutoConfiguration
Review Comment:
This is the one conversion in the PR that does not preserve its FQCN: `org.grails.plugins.core.CoreAutoConfiguration` becomes `org.grails.plugins.CoreAutoConfiguration`, because the generated sibling always takes the plugin class's package and `CoreGrailsPlugin` lives in `org.grails.plugins`.
The failure is silent in the direction that matters. Spring Boot only reports invalid `spring.autoconfigure.exclude` entries for classes still on the classpath, so an upgraded app excluding the old name gets no warning and has `classLoader`, `grailsConfigProperties` and `propertySourcesPlaceholderConfigurer` registered anyway. `@AutoConfigureAfter(name = "org.grails.plugins.core.CoreAutoConfiguration")` in third-party code goes quiet the same way.
`autoConfigurationName` cannot cover this — the package is hardcoded from the plugin class (`GrailsBeansASTTransformation.java:295-297`) and dotted values are rejected as invalid identifiers (line 368).
The upgrade guide currently documents exactly one of the four FQCN changes this PR makes: `GrailsDomainClassAutoConfiguration` → `org.grails.plugins.domain.DomainClassAutoConfiguration`, at `upgrading80x.adoc:1582`, complete with the "update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry" wording. `CoreAutoConfiguration`'s package move, `GrailsCacheAutoConfiguration` → `CacheAutoConfiguration`, and `DataBindingConfiguration` → `DataBindingAutoConfiguration` are not mentioned anywhere in the guide. Either let `autoConfigurationName` accept a fully-qualified name, or give the other three the same treatment line 1582 already gives the first.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "bean(...) must end with a factory closure: bean(Type) { ... }");
+ return;
+ }
+ ClosureExpression factory = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ typeAndName.type.getType(),
+ factory.getParameters() == null ? Parameter.EMPTY_ARRAY : factory.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ factory.getCode());
+ beanMethod.addAnnotation(beanAnnotation(typeAndName.name));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = owner.getField(fieldName);
+ if (field != null && field.isStatic() && field.isFinal() &&
+ field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
+ return value instanceof String ? (String) value : null;
+ }
+ catch (ReflectiveOperationException | RuntimeException | LinkageError ignored) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ private void processMethodStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "method(...) must end with a body closure: method(\"name\", Type) { ... }");
+ return;
+ }
+ ClosureExpression body = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, METHOD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ MethodNode helperMethod = new MethodNode(
+ typeAndName.name,
+ Modifier.PRIVATE,
+ typeAndName.type.getType(),
+ body.getParameters() == null ? Parameter.EMPTY_ARRAY : body.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ body.getCode());
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyGenericAnnotation(helperMethod, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(helperMethod);
+ }
+
+ private static final class TypeAndName {
+ private final ClassExpression type;
+ private final String name;
+
+ TypeAndName(ClassExpression type, String name) {
+ this.type = type;
+ this.name = name;
+ }
+ }
+
+ private TypeAndName parseNameAndType(List<Expression> args, MethodCallExpression call, SourceUnit source,
+ String callName, boolean requireValidIdentifier) {
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ if (args.size() == 2 && args.get(0) instanceof ClassExpression) {
+ addError(call, source, callName + "(...) takes the name before the type: " +
+ callName + "(\"myGreeter\", Greeter), not " + callName + "(Greeter, \"myGreeter\")");
+ }
+ else {
+ addError(call, source, callName + "(...) requires a type, optionally preceded by a name, " +
+ "e.g. " + callName + "(Greeter) or " + callName + "(\"myGreeter\", Greeter)");
+ }
+ return null;
+ }
+ ClassExpression type = (ClassExpression) args.get(args.size() - 1);
+
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(type.getType().getNameWithoutPackage());
Review Comment:
`requireValidIdentifier` is only consulted in the explicit-name branch below (line 981), so a convention-derived name is never checked.
Verified on this branch — `field('boolean', Boolean)` is correctly rejected:
```
"boolean" is not a valid name: it becomes the generated member's name,
so it must be a valid Java identifier
```
but the equivalent `field(Boolean)` compiles, and `Introspector.decapitalize("Boolean")` hands it a Java keyword for a name:
```
declaredFields : [boolean:Boolean]
FIELD name='boolean' type=java.lang.Boolean isJavaIdentifier=false
```
`field(Long)` produces a field named `long` and `method(Class) { }` a method named `class`, the same way — members no closure body can then reference. Moving the check so it also covers the derived name would make the two spellings agree.
##########
grails-doc/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc:
##########
@@ -119,6 +119,143 @@ class I18nGrailsPlugin extends Plugin {
A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.
+==== Compiling Bean Definitions into a Spring Boot AutoConfiguration
+
+
+`beanRegistrar()` and `doWithSpring` register beans at a single, fixed point in startup: before Spring Boot processes any `{springbootapi}org/springframework/boot/autoconfigure/AutoConfiguration.html[AutoConfiguration]`. That is enough for a bean to win against a Boot default guarded by `@ConditionalOnMissingBean`, but it cannot express ordering *relative to a specific* auto-configuration — running before `WebMvcAutoConfiguration` but after `MessageSourceAutoConfiguration`, say, regardless of where those two land in Boot's overall sort. Only a real `AutoConfiguration` class can declare that ordering, via `@AutoConfiguration(before = ..., after = ...)`.
+
+The link:{api}grails/compiler/beans/GrailsBeans.html[GrailsBeans] annotation lets you author bean definitions with DSL syntax similar to the classic Beans DSL, while compiling them at build time into genuine `@Bean` factory methods on a plain `AutoConfiguration` class — no closures, and nothing DSL-specific, survive into the compiled bytecode. Add `org.apache.grails:grails-beans-dsl` as a dependency and annotate a class whose `beans` property is a closure of `bean(["name", ] Type) { ... }` statements:
+
+[source,groovy]
+----
+import grails.compiler.beans.GrailsBeans
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration
+import org.springframework.context.MessageSource
+import org.springframework.context.support.ReloadableResourceBundleMessageSource
+import org.springframework.web.servlet.i18n.CookieLocaleResolver
+import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
+
+@GrailsBeans
+@AutoConfiguration(before = [MessageSourceAutoConfiguration, WebMvcAutoConfiguration])
+class I18nBeans {
+
+ def beans = {
+ bean('messageSource', ReloadableResourceBundleMessageSource) {
+ new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
+ }
+
+ bean('localeResolver', CookieLocaleResolver).conditionalOnMissingBean(CookieLocaleResolver) {
+ new CookieLocaleResolver('locale')
+ }
+
+ bean('localeChangeInterceptor', LocaleChangeInterceptor) { MessageSource messageSource ->
+ new LocaleChangeInterceptor(paramName: 'lang')
+ }
+ }
+}
+----
+
+Each `bean(["name", ] Type)` statement compiles to a public method returning the declared type and annotated `@Bean("name")`. The generated method's name is an implementation detail — Spring resolves the bean by its `@Bean("name")` value, never by the method name. It matches the bean name when that is a valid Java identifier not already taken by an existing member (declared, inherited, or defined elsewhere in the DSL — a bean named `toString` will not override `Object.toString()`); otherwise a synthesized `<type>$N` name (`service$0`, `service$1`, ...) is used instead, so any legal, non-blank Spring bean name compiles:
+
+* The bean name defaults to the decapitalized simple class name when omitted.
+* The same bean name may be declared by more than one `bean(...)` statement — the standard Spring Boot pattern for mutually exclusive variants of one bean, such as the framework's own `grailsUrlConverter` selected by `@ConditionalOnProperty` — provided every declaration with the name carries its own discriminating condition (such as `.annotate(ConditionalOnProperty, ...)`), so that at most one of them registers at runtime. Duplicating a bean name without that is a compile-time error, since Spring would keep the first definition and silently skip the rest.
+* Chaining `.conditionalOnMissingBean(...)` adds a `@ConditionalOnMissingBean` annotation to the generated method, matching Spring Boot's usual back-off semantics. It takes positional types (`.conditionalOnMissingBean(Greeter)`), the annotation's own named attributes (`.conditionalOnMissingBean(name: 'localeResolver', search: SearchStrategy.CURRENT)`), or both. With no arguments at all it compiles to the bare annotation, letting Spring Boot infer the back-off type from the method's return type — the recommended form when a bean simply backs off its own type, since `bean(AvailableLocaleResolver).conditionalOnMissingBean()` already says everything `.conditionalOnMissingBean(AvailableLocaleResolver)` would repeat.
+* Chaining `.conditionalOnMissingBeanName(...)` is the name-based counterpart: "register this bean unless a bean with *this bean's name* already exists". The condition's `name` member is set from the bean's own (explicit or convention-derived) name, so `bean(MessageSource).conditionalOnMissingBeanName(search: SearchStrategy.CURRENT) { ... }` states `messageSource` once and it feeds both `@Bean` and the condition — the two strings the explicit form has to keep in sync cannot diverge. It accepts the annotation's other attributes (`search:`, `ignored:`, ...) but rejects `name:` and types, which would contradict its purpose; use `.conditionalOnMissingBean(...)` for those.
+* Chaining `.primary()`, `.lazy()`, and/or `.scope("name")` adds `@Primary`, `@Lazy`, and `@Scope("name")` respectively.
+* Chaining `.staticMethod()` makes the generated factory method `static` — Spring's recommended shape for `BeanFactoryPostProcessor` and `BeanPostProcessor` beans, which must be creatable without instantiating their declaring configuration class. A static bean's closure cannot reference `field(...)` or `method(...)` members, since those are instance members; under `@CompileStatic` that mistake is a compile error.
+* Chaining `.annotate(AnnotationType[, attr: value, ...])` attaches any other single-valued annotation directly — any `@Conditional*` (built-in or a custom `Condition`), `@Order`, `@DependsOn`, or anything else a hand-written `@Bean` method could carry. It's repeatable, so several different annotations can be chained onto the same bean: `bean('special', Special).annotate(Order, value: 1).annotate(ConditionalOnProperty, prefix: 'myapp', name: 'enabled', havingValue: 'true') { ... }`.
+* Any combination of the above can be chained together, in any order — for example `bean('slowGreeter', SlowGreeter).lazy().scope('prototype') { ... }`.
+* Typed closure parameters (`{ MessageSource messageSource -> ... }`) become the generated method's parameters, so other beans are injected the same way a hand-written `@Bean` method would declare them — and a parameter-level annotation such as `{ @Qualifier('special') Greeter g -> ... }` carries straight through too, since the closure's own parameters become the generated method's parameters directly.
+
+Two more statement kinds can appear inside `beans { }` alongside `bean(...)`, for state and logic shared across bean methods — the same role a hand-written `@Configuration` class's own fields and private methods play:
+
+* `field(["name", ] Type)`, optionally chained with `.value(...)` and/or (repeatably) `.annotate(AnnotationType[, attr: value, ...])`, declares a private field on the generated class. The usual case is injected configuration, and `.value(...)` covers it directly: `field('encoding', String).value('grails.gsp.view.encoding', 'UTF-8')` compiles to `@Value("${grails.gsp.view.encoding:UTF-8}")`. The two-argument form takes a config key and default — and because the DSL builds the placeholder itself, the key may be a bare constant reference (`.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')`), the one shape a directly-written annotation value can't accept. The one-argument form takes a bare config key with no default — `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` — while a string already containing a `${...}` placeholder or a `#{...}` SpEL expression passes through verbatim: `.value('#{T(java.lang.Runtime).getRuntime().availab
leProcessors()}')`.
+* `method(["name", ] Type) { ... }`, chainable with `.annotate(...)` only (`.value(...)` is field-specific), declares a private helper method the same way `bean(...)` declares a public one — typed closure parameters become method parameters, and the closure body becomes the method body.
+
+Both are ordinary private members of the generated class, so a `bean(...)` closure reads a `field(...)` or calls a `method(...)` exactly like a hand-written `@Bean` method would reference a sibling field or method on its own class:
+
+[source,groovy]
+----
+field('suffix', String).value('myapp.greeting-suffix', '!')
+
+method('buildGreeting', String) { String name ->
+ "Hello, ${name}${suffix}"
+}
+
+bean('greeting', Greeting) {
+ new Greeting(buildGreeting('World'))
+}
+----
+
+Because the result is an ordinary `AutoConfiguration` class, it must be registered the same way any Spring Boot auto-configuration is: listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`. Modules built as part of this project can apply the `org.apache.grails.buildsrc.autoconfiguration-imports` Gradle convention plugin to generate that file automatically, by scanning the module's own compiled classes for `@AutoConfiguration` at build time. Projects outside this build register the class the same way any hand-written `AutoConfiguration` is registered — by listing it in that file directly.
+
+NOTE: `@GrailsBeans` does not require extending `Plugin` at all — it produces a plain Spring Boot `AutoConfiguration`, so it can be used by any Spring Boot module, not just a Grails plugin descriptor. Applications can use it too, including directly on the `Application` class — where no imports-file registration is needed, since Spring Boot processes the application class itself — see link:spring.html#springdslAdditional[Configuring Additional Beans]. Within a plugin, reach for it specifically when a bean's registration needs to be ordered against a particular other auto-configuration; otherwise `beanRegistrar()` remains the recommended way to register beans from a `Plugin`.
+
+The DSL still covers a narrower surface than `doWithSpring(BeanBuilder)`:
+
+* Each top-level statement inside `beans { }` must be exactly `bean(...)`, `field(...)`, or `method(...)`, with their respective chaining — an `if`, a `for` loop, or any other imperative Groovy directly inside `beans { }` is a compile-time error, not a runtime one. Note that this is about the DSL's own top-level statements, not the bodies of `bean(...)`/`method(...)` closures themselves, which accept arbitrary Groovy — and `field(...)`/`method(...)` already cover the common reasons to want shared state or logic in the first place.
+* `.annotate(...)` attribute values must be simple compile-time constants (strings, numbers, booleans, class literals, enum constants, or arrays of these) — an annotation attribute that itself takes a nested annotation as a value isn't supported.
Review Comment:
This bullet is both stricter than reality and not specific enough about the real edge — and it is the bullet that sent `UrlMappingsGrailsPlugin` to hardcoded property strings.
A bare constant reference **is** accepted as an `.annotate(...)` attribute value, `@CompileStatic` included. I compiled the variants; the discriminator is not "constant literal vs constant reference" but whether the reference resolves to a genuine `public static final` field:
| constant owner | `@CompileStatic` | result |
| --- | --- | --- |
| interface constant (anything on `grails.config.Settings`) | yes | works |
| Java constant, or explicitly `public static final` Groovy field | yes | works |
| Groovy `static final String X = ...` — i.e. a *property*, with a generated getter | yes | **fails** |
| any of the above | no | works |
`grails.config.Settings` is an `interface`, so every `Settings.*` constant is a real field with no accessor and folds correctly. A plain Groovy class's `static final` is a property, and `@CompileStatic` rewrites the reference into a method call:
```
Expected 'Settings.getWEB_URL_CONVERTER()' to be an inline constant of type java.lang.String
```
Separately, a *concatenation* of constants never folds in `.annotate(...)` under `@CompileStatic` (see my note on `addMembersFromMap`) — which is the one thing `.value(...)` does handle and `.annotate(...)` does not.
Worth restating the bullet in those terms. As written it steers readers away from the `Settings` constants they should be using, and says nothing about the case that actually breaks.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
Review Comment:
Neither this `ClassNode` nor any of the synthesized `MethodNode`/`FieldNode`/`AnnotationNode`s gets `setSourcePosition(...)` — there are no calls to it anywhere in the file. Anything Groovy reports against a generated node afterwards therefore has no location:
```
-1: 'valu' is not part of the annotation Order in @org.springframework.core.annotation.Order
@ line -1, column -1
```
That is the diagnostic a user gets for a typo in the public `.annotate(...)` escape hatch, and a sibling name clash reports `Invalid duplicate class definition ... @ line -1, column -1` the same way. Copying the position from the originating `MethodCallExpression` (and from the plugin class for the sibling) would make these point at the offending DSL statement.
##########
grails-beans-dsl-plugin-example/src/main/groovy/beandsl/example/plugin/GreetingGrailsPlugin.groovy:
##########
@@ -0,0 +1,52 @@
+/*
+ * 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 beandsl.example.plugin
+
+import org.springframework.beans.factory.annotation.Value
+import org.springframework.boot.autoconfigure.AutoConfiguration
+
+import grails.compiler.beans.GrailsBeans
+import grails.plugins.Plugin
+
+/**
+ * Demonstrates {@code field(...)} and {@code method(...)} - the same shape real autoconfigurations
+ * like the built-in i18n plugin's need: injected configuration shared across beans, and a private
+ * helper factored out of a bean's construction logic. Both compile onto the generated
+ * {@code GreetingGrailsPluginAutoConfiguration} sibling as ordinary private members, exactly like
Review Comment:
`defaultSiblingSimpleName` strips the `GrailsPlugin` suffix, so this generates `GreetingAutoConfiguration`, not `GreetingGrailsPluginAutoConfiguration`. `FarewellGrailsPlugin` gets it right and `FarewellGrailsPluginAutoDiscoverySpec:71` asserts the name via `Class.forName`; the Greeting spec never does, which is why nothing caught this.
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/AutoConfigurationImportsPlugin.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.buildsrc
+
+import groovy.transform.CompileStatic
+
+import org.gradle.api.Plugin
+import org.gradle.api.Project
+import org.gradle.api.file.Directory
+import org.gradle.api.plugins.JavaPluginExtension
+import org.gradle.api.provider.Provider
+import org.gradle.api.tasks.SourceSet
+import org.gradle.api.tasks.TaskProvider
+
+/**
+ * Convention plugin that wires {@link GenerateAutoConfigurationImportsTask} into the {@code main}
+ * source set's output, so a module authoring {@code @AutoConfiguration} classes never has to
+ * hand-maintain {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}.
+ *
+ * <p>The generated resources directory is registered via {@code sourceSets.main.output.dir(...)}
+ * rather than routed through {@code processResources}, so it lands on the compile/runtime/test
+ * classpath and in the final jar without depending on {@code Copy}-task ordering semantics.
+ */
+@CompileStatic
+class AutoConfigurationImportsPlugin implements Plugin<Project> {
+
+ static final String TASK_NAME = 'generateAutoConfigurationImports'
+ static final String GENERATED_RESOURCES_PATH = 'generated/resources/autoConfigurationImports'
+
+ @Override
+ void apply(Project project) {
+ project.pluginManager.apply('java-base')
+
+ SourceSet main = project.extensions.getByType(JavaPluginExtension).sourceSets.getByName('main')
+ Provider<Directory> generatedDir = project.layout.buildDirectory.dir(GENERATED_RESOURCES_PATH)
+
+ TaskProvider<GenerateAutoConfigurationImportsTask> task = project.tasks.register(
+ TASK_NAME, GenerateAutoConfigurationImportsTask) { GenerateAutoConfigurationImportsTask t ->
+ t.group = 'build'
+ t.description = 'Generates META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports ' +
+ 'by scanning compiled classes for @AutoConfiguration'
+ t.classesDirs.from(main.output.classesDirs)
+ t.scanClasspath.from(main.compileClasspath, main.output.classesDirs)
+ t.outputDirectory.set(generatedDir)
+ }
+
+ main.output.dir(Collections.<String, Object> singletonMap('builtBy', task), generatedDir)
Review Comment:
Registering the generated directory on `main.output` puts it at the same archive path as a hand-maintained `src/main/resources/META-INF/spring/...AutoConfiguration.imports` that `processResources` also contributes, so a module with both feeds the resource twice into the jar. Nothing in the PR exercises that combination — and it is the state every converted module would be in the moment this plugin is applied to them, since all five still hand-maintain their imports file.
Related: the only consumers of this convention plugin are the two new example modules; no production module applies it. Applying it to at least one of the converted modules would both remove a hand-maintained file and cover the collision case. As it stands the plugin, its task and its spec are carried by the build without a real consumer.
##########
build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GenerateAutoConfigurationImportsTask.groovy:
##########
@@ -0,0 +1,133 @@
+/*
+ * 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.buildsrc
+
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.ConfigurableFileCollection
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.tasks.Classpath
+import org.gradle.api.tasks.IgnoreEmptyDirectories
+import org.gradle.api.tasks.InputFiles
+import org.gradle.api.tasks.OutputDirectory
+import org.gradle.api.tasks.PathSensitive
+import org.gradle.api.tasks.PathSensitivity
+import org.gradle.api.tasks.TaskAction
+
+/**
+ * Scans this project's own compiled main classes for {@code @AutoConfiguration} and writes
+ * {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the
+ * file never needs to be hand-maintained. Mirrors how {@code META-INF/grails-plugin.xml} is already
+ * generated from scanned {@code *GrailsPlugin} classes elsewhere in this build.
+ *
+ * <p>Classes are inspected via a scratch {@link URLClassLoader} over this project's own runtime
+ * classpath, isolated from the Gradle daemon's classpath (parent set to the platform loader) so a
+ * different Spring/Groovy version on the daemon's classpath cannot shadow the project's own.
+ */
+abstract class GenerateAutoConfigurationImportsTask extends DefaultTask {
+
+ static final String IMPORTS_RESOURCE_PATH =
+ 'META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports'
+
+ static final String AUTO_CONFIGURATION_ANNOTATION = 'org.springframework.boot.autoconfigure.AutoConfiguration'
+
+ @InputFiles
+ @IgnoreEmptyDirectories
+ @PathSensitive(PathSensitivity.RELATIVE)
+ abstract ConfigurableFileCollection getClassesDirs()
+
+ /**
+ * The classpath the scratch classloader resolves annotations/supertypes against. Deliberately
+ * built from the project's compile classpath (dependencies only) rather than its runtime
+ * classpath: the runtime classpath includes the source set's own output, which - once this
+ * task's generated directory is registered on that same output - would make this task depend
+ * on itself.
+ */
+ @Classpath
+ abstract ConfigurableFileCollection getScanClasspath()
+
+ @OutputDirectory
+ abstract DirectoryProperty getOutputDirectory()
+
+ @TaskAction
+ void generate() {
+ SortedSet<String> discovered = scan(classesDirs.files, scanClasspath.files) { String className, Throwable failure ->
+ logger.warn('generateAutoConfigurationImports: could not inspect {} - it will be excluded from ' +
+ 'the generated imports file even if it is genuinely annotated @AutoConfiguration. Cause: {}',
+ className, failure.toString())
+ }
+ File importsFile = outputDirectory.file(IMPORTS_RESOURCE_PATH).get().asFile
+ importsFile.parentFile.mkdirs()
+ importsFile.text = discovered.isEmpty() ? '' : discovered.join('\n') + '\n'
+ }
+
+ /**
+ * Package-private so it is directly unit-testable without running a real Gradle task.
+ *
+ * @param classesDirs directories of compiled {@code .class} files to inspect (a project's own
+ * output only - dependency jars on {@code classpathFiles} are never scanned for candidates)
+ * @param classpathFiles the classpath the scratch classloader resolves supertypes/annotations
+ * against; must include {@code classesDirs} plus every runtime dependency
+ * @param onUnresolvable invoked with (className, failure) for every candidate class that could
+ * not be loaded against {@code classpathFiles}. Defaults to a no-op so existing callers are
+ * unaffected; {@link #generate()} passes a callback that logs a build warning, since a class
+ * that fails to load here is silently excluded from the generated imports file - which, if it
+ * was genuinely a real {@code @AutoConfiguration}, means its beans would never be registered
+ * with no other signal that anything went wrong.
+ * @return the fully-qualified names of every top-level class annotated {@code @AutoConfiguration},
+ * sorted for a deterministic, diff-friendly output file
+ */
+ static SortedSet<String> scan(Set<File> classesDirs, Set<File> classpathFiles,
+ Closure<?> onUnresolvable = { String className, Throwable failure -> }) {
+ URL[] urls = classpathFiles.collect { it.toURI().toURL() } as URL[]
+ URLClassLoader scanLoader = new URLClassLoader(urls, ClassLoader.systemClassLoader.parent)
+ try {
+ Class<?> autoConfigurationAnnotation = Class.forName(AUTO_CONFIGURATION_ANNOTATION, false, scanLoader)
+ SortedSet<String> discovered = new TreeSet<>()
+ classesDirs.each { dir -> scanDirectory(dir, scanLoader, autoConfigurationAnnotation, discovered, onUnresolvable) }
+ discovered
+ }
+ finally {
+ scanLoader.close()
+ }
+ }
+
+ private static void scanDirectory(File dir, URLClassLoader scanLoader, Class<?> autoConfigurationAnnotation,
+ SortedSet<String> discovered, Closure<?> onUnresolvable) {
+ if (!dir.exists()) {
+ return
+ }
+ dir.eachFileRecurse(groovy.io.FileType.FILES) { file ->
+ if (!file.name.endsWith('.class') || file.name.contains('$')) {
+ return
+ }
+ String relative = dir.toPath().relativize(file.toPath()).toString()
+ String className = relative.replace(File.separator, '.') - '.class'
Review Comment:
Groovy's `String.minus` removes the *first* occurrence, not a trailing extension. Since the separators have already been replaced with `.`, any package segment beginning with `class` gets mangled:
`org/grails/plugins/classloading/FooAutoConfiguration.class` → `org.grails.pluginsloading.FooAutoConfiguration.class`
`Class.forName` then fails, the `catch (Throwable)` below turns it into a `logger.warn`, and the class is silently left out of the generated imports file — exactly the outcome the warning callback was added to make visible, but for a reason that is a bug rather than a genuinely unresolvable class. `relative[0..<relative.length() - 6]` or `removeSuffix`-style handling fixes it.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
Review Comment:
Any argument-bearing `.conditionalOnMissingBean(...)` counts as discriminating here, including a purely name-based one. The comment above `validateSharedBeanNames` excludes `.conditionalOnMissingBeanName()` and bare `.conditionalOnMissingBean()` because they are "identical on every duplicate by construction, so [they] can never tell them apart" — but `.conditionalOnMissingBean(name: ...)` is identical in effect whenever the duplicates share a name, which is the only situation this validation runs in.
Verified — this compiles with no error on the current branch:
```groovy
bean('greeting', String).conditionalOnMissingBean(name: 'greeting') { 'a' }
bean('greeting', String).conditionalOnMissingBean(name: 'greeting') { 'b' }
```
```
COMPILED OK <-- NO ERROR
method 'greeting' : @Bean value()=[greeting], MERGED name=[greeting]
method 'string$0' : @Bean value()=[greeting], MERGED name=[greeting]
```
Spring keeps the first definition and drops the second — the copy-paste accident the check exists to catch. The bare `.conditionalOnMissingBean()`, `.conditionalOnMissingBeanName()` and no-qualifier spellings of the same pair all error as intended, so the hole is specific to the argument-bearing form. `.conditionalOnMissingBean(name: 'somethingElse')` passes too, incidentally — the argument does not have to relate to the bean at all.
Is treating a `name:`/`search:`-only map like the bare form (i.e. only a positional type, or a `@Conditional`-meta-annotated `.annotate(...)`, discriminates) what you intended here?
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "bean(...) must end with a factory closure: bean(Type) { ... }");
+ return;
+ }
+ ClosureExpression factory = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ typeAndName.type.getType(),
+ factory.getParameters() == null ? Parameter.EMPTY_ARRAY : factory.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ factory.getCode());
+ beanMethod.addAnnotation(beanAnnotation(typeAndName.name));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = owner.getField(fieldName);
+ if (field != null && field.isStatic() && field.isFinal() &&
+ field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
Review Comment:
`getTypeClass()` throws `GroovyBugError`, which extends `AssertionError` — so it escapes the `ReflectiveOperationException | RuntimeException | LinkageError` catch below and aborts the whole compilation with an internal compiler error rather than the intended located DSL message.
I mapped the precondition against this branch. The crash needs the AST branch above to miss **and** the owner to be a same-compilation-unit (unresolved, primary) `ClassNode`, for which `getTypeClass()` always throws. The AST branch misses for anything `ClassNode.getField(name)` cannot see — it walks superclasses but never interfaces — and, of course, for a name that does not exist:
| `.value(...)` constant owner | outcome |
| --- | --- |
| same-unit class, constant declared directly | OK |
| same-unit class, constant on a same-unit superclass | OK |
| same-unit interface extending a same-unit interface | **`BUG!` abort** |
| same-unit class implementing a same-unit interface | **`BUG!` abort** |
| same-unit class, typo'd / non-existent constant | **`BUG!` abort** |
| already-compiled owner, interface-inherited constant | OK — `Class.getField` does walk interfaces |
| already-compiled owner, typo'd constant | clean located error |
So the simplest reproducer is not exotic at all — it is a typo against a constant declared in the same file:
```groovy
@GrailsBeans
@AutoConfiguration
class ProbeBeans {
def beans = {
field('thing', String).value(SameFileKeys.NO_SUCH_KEY, 'fallback')
}
}
```
```
BUG! exception in phase 'canonicalization' in source unit '...'
ClassNode#getTypeClass for SameFileKeys called before the type class is set
at org.codehaus.groovy.ast.ClassNode.getTypeClass(ClassNode.java:1417)
at org.grails.compiler.beans.GrailsBeansASTTransformation.resolveStringConstant(GrailsBeansASTTransformation.java:888)
```
The identical mistake against a classpath owner produces the message that was intended:
```
.value(...) arguments must be compile-time String constants (a literal, a static final
constant reference, or a concatenation of those)
```
Please guard with `owner.isResolved()` before `getTypeClass()`, search interfaces in the AST lookup, and add a test — right now nothing covers an unresolvable `.value(...)` constant at all.
##########
grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPlugin.groovy:
##########
@@ -51,15 +72,55 @@ class UrlMappingsGrailsPlugin extends Plugin {
def dependsOn = [core: version]
def loadAfter = ['controllers']
+ def beans = {
+ field('cacheUrls', Boolean).value(Settings.WEB_LINK_GENERATOR_USE_CACHE, '#{null}')
+ field('serverURL', String).value(Settings.SERVER_URL, '#{null}')
+
+ // The two mutually exclusive grailsUrlConverter variants share one bean name; the
+ // @ConditionalOnProperty selects which registers. Its name: attribute must be an inline
+ // constant, so the property names below are literals mirroring Settings.WEB_URL_CONVERTER
Review Comment:
The justification in this comment does not hold. `grails.config.Settings` is an `interface` (`Settings.groovy:28`), so `Settings.WEB_URL_CONVERTER` is a genuine `public static final` field with no accessor — exactly the shape `.annotate(...)` folds correctly, `@CompileStatic` included. I compiled this form against the branch and it produces `name = ["grails.web.url.converter"]` as expected:
```groovy
bean('grailsUrlConverter', UrlConverter).conditionalOnMissingBeanName()
.annotate(ConditionalOnProperty, name: Settings.WEB_URL_CONVERTER, havingValue: 'camelCase', matchIfMissing: true)
```
(What `.annotate(...)` genuinely cannot fold under `@CompileStatic` is a *concatenation* of constants, and a `static final` declared on a Groovy *class* — where it is a property with a generated getter. Neither applies to `Settings`.)
The literals match `Settings` today, so nothing is broken right now, but they are a second copy of the same keys with nothing keeping them in step — a change to `Settings.WEB_URL_CONVERTER` or `Settings.SETTING_CORS_FILTER` would silently stop selecting the right converter. Note the two `field(...)` statements immediately above already use `Settings.WEB_LINK_GENERATOR_USE_CACHE` and `Settings.SERVER_URL`, so the file is inconsistent with itself. Using the constants here too removes the duplication and the comment.
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "bean(...) must end with a factory closure: bean(Type) { ... }");
+ return;
+ }
+ ClosureExpression factory = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ typeAndName.type.getType(),
+ factory.getParameters() == null ? Parameter.EMPTY_ARRAY : factory.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ factory.getCode());
+ beanMethod.addAnnotation(beanAnnotation(typeAndName.name));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = owner.getField(fieldName);
+ if (field != null && field.isStatic() && field.isFinal() &&
+ field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
+ return value instanceof String ? (String) value : null;
+ }
+ catch (ReflectiveOperationException | RuntimeException | LinkageError ignored) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ private void processMethodStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "method(...) must end with a body closure: method(\"name\", Type) { ... }");
+ return;
+ }
+ ClosureExpression body = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, METHOD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ MethodNode helperMethod = new MethodNode(
+ typeAndName.name,
+ Modifier.PRIVATE,
+ typeAndName.type.getType(),
+ body.getParameters() == null ? Parameter.EMPTY_ARRAY : body.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ body.getCode());
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyGenericAnnotation(helperMethod, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(helperMethod);
+ }
+
+ private static final class TypeAndName {
+ private final ClassExpression type;
+ private final String name;
+
+ TypeAndName(ClassExpression type, String name) {
+ this.type = type;
+ this.name = name;
+ }
+ }
+
+ private TypeAndName parseNameAndType(List<Expression> args, MethodCallExpression call, SourceUnit source,
+ String callName, boolean requireValidIdentifier) {
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ if (args.size() == 2 && args.get(0) instanceof ClassExpression) {
+ addError(call, source, callName + "(...) takes the name before the type: " +
+ callName + "(\"myGreeter\", Greeter), not " + callName + "(Greeter, \"myGreeter\")");
+ }
+ else {
+ addError(call, source, callName + "(...) requires a type, optionally preceded by a name, " +
+ "e.g. " + callName + "(Greeter) or " + callName + "(\"myGreeter\", Greeter)");
+ }
+ return null;
+ }
+ ClassExpression type = (ClassExpression) args.get(args.size() - 1);
+
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(type.getType().getNameWithoutPackage());
+ }
+ else {
+ Expression nameArg = args.get(0);
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, callName + "(name, Type) requires the name to be a String literal, " +
+ "e.g. " + callName + "(\"myGreeter\", Greeter)");
+ return null;
+ }
+ name = (String) nameValue;
+ if (requireValidIdentifier && !isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "\"" + name + "\" is not a valid name: it becomes the generated " +
+ "member's name, so it must be a valid Java identifier");
+ return null;
+ }
+ // Even bean(...), which otherwise allows any Spring name, must reject a blank one:
+ // Spring treats a blank @Bean name as absent and falls back to the method name, so
+ // the name actually written would be silently discarded.
+ if (!requireValidIdentifier && name.isBlank()) {
+ addError(nameArg, source, callName + "(name, Type) requires a non-blank name");
+ return null;
+ }
+ }
+ return new TypeAndName(type, name);
+ }
+
+ private boolean applyQualifier(MethodNode beanMethod, String beanName, MethodCallExpression qualifierCall,
+ List<Expression> args, SourceUnit source) {
+ String name = qualifierCall.getMethodAsString();
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(name)) {
+ AnnotationNode annotation = conditionalOnMissingBeanAnnotation(args, qualifierCall, source);
+ return annotation != null && addAnnotationIfAbsent(beanMethod, qualifierCall, annotation, source);
+ }
+ if (CONDITIONAL_ON_MISSING_BEAN_NAME_CALL.equals(name)) {
+ AnnotationNode annotation = conditionalOnMissingBeanNameAnnotation(args, beanName, qualifierCall, source);
+ return annotation != null && addAnnotationIfAbsent(beanMethod, qualifierCall, annotation, source);
+ }
+ if (PRIMARY_CALL.equals(name) || LAZY_CALL.equals(name)) {
+ if (!args.isEmpty()) {
+ addError(qualifierCall, source, "." + name + "() takes no arguments");
+ return false;
+ }
+ Class<?> annotationType = PRIMARY_CALL.equals(name) ? Primary.class : Lazy.class;
+ return addAnnotationIfAbsent(beanMethod, qualifierCall,
+ new AnnotationNode(ClassHelper.make(annotationType)), source);
+ }
+ // Generates a static factory method - Spring's recommended shape for a
+ // BeanFactoryPostProcessor/BeanPostProcessor bean, which must be creatable without
+ // instantiating its declaring configuration class. The body consequently cannot touch
+ // field(...)/method(...) members, which are instance members of that class.
+ if (STATIC_METHOD_CALL.equals(name)) {
+ if (!args.isEmpty()) {
+ addError(qualifierCall, source, ".staticMethod() takes no arguments");
+ return false;
+ }
+ beanMethod.setModifiers(beanMethod.getModifiers() | Modifier.STATIC);
+ return true;
+ }
+ if (SCOPE_CALL.equals(name)) {
+ return applyScopeQualifier(beanMethod, qualifierCall, args, source);
+ }
+ return applyGenericAnnotation(beanMethod, qualifierCall, args, source);
+ }
+
+ private boolean applyScopeQualifier(MethodNode beanMethod, MethodCallExpression qualifierCall,
+ List<Expression> args, SourceUnit source) {
+ Expression scopeArg = args.size() == 1 ? args.get(0) : null;
+ Object scopeValue = scopeArg instanceof ConstantExpression ? ((ConstantExpression) scopeArg).getValue() : null;
+ if (!(scopeValue instanceof String) || ((String) scopeValue).isEmpty()) {
+ addError(qualifierCall, source, ".scope(...) requires exactly one non-empty String argument, " +
+ "e.g. .scope(\"prototype\")");
+ return false;
+ }
+ AnnotationNode scopeAnnotation = new AnnotationNode(ClassHelper.make(Scope.class));
+ scopeAnnotation.setMember("value", scopeArg);
+ return addAnnotationIfAbsent(beanMethod, qualifierCall, scopeAnnotation, source);
+ }
+
+ private boolean applyGenericAnnotation(AnnotatedNode target, MethodCallExpression qualifierCall,
+ List<Expression> args, SourceUnit source) {
+ MapExpression members = !args.isEmpty() && args.get(0) instanceof MapExpression ? (MapExpression) args.get(0) : null;
+ List<Expression> remaining = members != null ? args.subList(1, args.size()) : args;
+ if (remaining.size() != 1 || !(remaining.get(0) instanceof ClassExpression)) {
+ addError(qualifierCall, source, ".annotate(...) requires an annotation type as its only " +
+ "positional argument, e.g. .annotate(Order, value: 1) or .annotate(ConditionalOnWebApplication)");
+ return false;
+ }
+
+ ClassNode annotationType = ((ClassExpression) remaining.get(0)).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(qualifierCall, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ return false;
+ }
+
+ AnnotationNode annotation = new AnnotationNode(annotationType);
+ if (members != null && !addMembersFromMap(annotation, members, qualifierCall, source)) {
+ return false;
+ }
+ return addAnnotationIfAbsent(target, qualifierCall, annotation, source);
+ }
+
+ private boolean addMembersFromMap(AnnotationNode annotation, MapExpression members,
+ MethodCallExpression qualifierCall, SourceUnit source) {
+ for (MapEntryExpression entry : members.getMapEntryExpressions()) {
+ Object keyValue = entry.getKeyExpression() instanceof ConstantExpression ?
+ ((ConstantExpression) entry.getKeyExpression()).getValue() : null;
+ if (!(keyValue instanceof String)) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() +
+ "(...) attribute names must be simple identifiers, e.g. .annotate(Order, value: 1)");
+ return false;
+ }
+ annotation.setMember((String) keyValue, entry.getValueExpression());
Review Comment:
`.annotate(...)` attaches the raw value expression, while `.value(...)` deliberately folds its arguments into a constant first — with a comment (lines 810-813) explaining exactly why: under `@CompileStatic` the static compiler rewrites `+` into `.plus()` before Groovy's annotation folding runs. That reasoning applies verbatim here, but the folding is missing.
Verified both ways. The concatenation shape the spec exercises compiles without `@CompileStatic` and fails with it — and the fixture at `GrailsBeansASTTransformationSpec.groovy:828-853` carries only `@GrailsBeans` + `@AutoConfiguration`, so the statically-compiled case is never covered:
```groovy
@GrailsBeans
@CompileStatic
@AutoConfiguration
class Fixture {
def beans = {
field('localeResolverType', String).annotate(Value, value: '${' + Settings.I18N_LOCALE_RESOLVER + ':session}')
}
}
```
```
Expected '${.plus(grails.config.Settings.I18N_LOCALE_RESOLVER).plus(:session})' to be an inline constant
of type java.lang.String in @org.springframework.beans.factory.annotation.Value
Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object'
```
Fair on severity: this is a clean, located compile error, not a crash — the shape is simply unavailable under `@CompileStatic`, which is the mode every conversion in this PR uses. It fails identically whether `Settings` is same-unit or the real `grails.config.Settings`, confirming the trigger is purely the `+` → `.plus()` rewrite. `.value(Settings.I18N_LOCALE_RESOLVER, 'session')` folds fine, so a workaround exists for `@Value` specifically; there is none for any other annotation.
Running `resolveStringConstant` over String-valued attributes in `addMembersFromMap` would close the gap and make the two qualifiers consistent. Whichever way it goes, the test at line 842 should be duplicated under `@CompileStatic`, since its `given:` block currently claims to prove a general rule it only demonstrates for dynamic classes.
##########
grails-core/build.gradle:
##########
@@ -51,6 +51,8 @@ dependencies {
api 'jakarta.persistence:jakarta.persistence-api'
api 'jakarta.annotation:jakarta.annotation-api'
+ api project(':grails-beans-dsl')
Review Comment:
`grails-beans-dsl` is now declared in three different scopes across nine modules:
| scope | modules |
| --- | --- |
| `api` | `grails-core` |
| `implementation` | `grails-cache`, `grails-databinding`, `grails-domain-class`, `grails-i18n`, `grails-url-mappings`, `grails-sitemesh3`, plus both example modules |
| `compileOnly` | `grails-mail` |
`api` here is the broadest of the three, and it looks deliberate rather than accidental: `GlobalGrailsClassInjectorTransformation.compileBeansDsl` reflectively loads `org.grails.compiler.beans.GrailsBeansASTTransformation` and silently returns if it is not on the compile classpath, so the implicit `def beans = { }` convention only reaches a third-party plugin author because `grails-core` exposes the transform transitively. `compileOnly` on `grails-core` would not achieve that. If that is the reasoning, it deserves a comment on this line — it is the load-bearing part of the convention, and nothing currently records it.
Two consequences worth deciding on explicitly:
1. Every module that already declares `api project(':grails-core')` — `grails-cache`, `grails-databinding`, `grails-domain-class`, `grails-sitemesh3` — receives `grails-beans-dsl` transitively, so their own `implementation project(':grails-beans-dsl')` lines are redundant.
2. `api` puts the AST transform, plus its own `api` dependencies on `spring-context` and `spring-boot-autoconfigure`, on every application's *runtime* classpath. `@GrailsBeans` is `RetentionPolicy.RUNTIME` (`GrailsBeans.java:99`), so the annotation really is written into the class files — but nothing reads it at runtime. `CLASS` retention would remove the need for runtime exposure without affecting the compile-classpath requirement above.
Either way, the nine declarations should agree on one story.
##########
grails-core/src/main/groovy/org/grails/compiler/injection/GlobalGrailsClassInjectorTransformation.groovy:
##########
@@ -179,6 +188,44 @@ class GlobalGrailsClassInjectorTransformation implements ASTTransformation, Comp
/**
* @return {@code true} when the {@code grails.isolated.build} system property is {@code true}.
*/
+ /**
Review Comment:
Inserting `compileBeansDsl` here has orphaned the javadoc that documented `isIsolatedBuild()`. There are now two consecutive javadoc blocks and the nearest one wins, so
```groovy
/**
* @return {@code true} when the {@code grails.isolated.build} system property is {@code true}.
*/
```
is a dangling `@return` on a `void` method, while `isIsolatedBuild()` (line 229) is left with no documentation at all.
Moving the new method below `isIsolatedBuild()`, or moving that block back down onto it, restores both.
##########
grails-doc/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc:
##########
@@ -119,6 +119,143 @@ class I18nGrailsPlugin extends Plugin {
A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.
+==== Compiling Bean Definitions into a Spring Boot AutoConfiguration
+
+
+`beanRegistrar()` and `doWithSpring` register beans at a single, fixed point in startup: before Spring Boot processes any `{springbootapi}org/springframework/boot/autoconfigure/AutoConfiguration.html[AutoConfiguration]`. That is enough for a bean to win against a Boot default guarded by `@ConditionalOnMissingBean`, but it cannot express ordering *relative to a specific* auto-configuration — running before `WebMvcAutoConfiguration` but after `MessageSourceAutoConfiguration`, say, regardless of where those two land in Boot's overall sort. Only a real `AutoConfiguration` class can declare that ordering, via `@AutoConfiguration(before = ..., after = ...)`.
+
+The link:{api}grails/compiler/beans/GrailsBeans.html[GrailsBeans] annotation lets you author bean definitions with DSL syntax similar to the classic Beans DSL, while compiling them at build time into genuine `@Bean` factory methods on a plain `AutoConfiguration` class — no closures, and nothing DSL-specific, survive into the compiled bytecode. Add `org.apache.grails:grails-beans-dsl` as a dependency and annotate a class whose `beans` property is a closure of `bean(["name", ] Type) { ... }` statements:
+
+[source,groovy]
+----
+import grails.compiler.beans.GrailsBeans
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration
+import org.springframework.context.MessageSource
+import org.springframework.context.support.ReloadableResourceBundleMessageSource
+import org.springframework.web.servlet.i18n.CookieLocaleResolver
+import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
+
+@GrailsBeans
+@AutoConfiguration(before = [MessageSourceAutoConfiguration, WebMvcAutoConfiguration])
+class I18nBeans {
+
+ def beans = {
+ bean('messageSource', ReloadableResourceBundleMessageSource) {
+ new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
+ }
+
+ bean('localeResolver', CookieLocaleResolver).conditionalOnMissingBean(CookieLocaleResolver) {
+ new CookieLocaleResolver('locale')
+ }
+
+ bean('localeChangeInterceptor', LocaleChangeInterceptor) { MessageSource messageSource ->
+ new LocaleChangeInterceptor(paramName: 'lang')
+ }
+ }
+}
+----
+
+Each `bean(["name", ] Type)` statement compiles to a public method returning the declared type and annotated `@Bean("name")`. The generated method's name is an implementation detail — Spring resolves the bean by its `@Bean("name")` value, never by the method name. It matches the bean name when that is a valid Java identifier not already taken by an existing member (declared, inherited, or defined elsewhere in the DSL — a bean named `toString` will not override `Object.toString()`); otherwise a synthesized `<type>$N` name (`service$0`, `service$1`, ...) is used instead, so any legal, non-blank Spring bean name compiles:
+
+* The bean name defaults to the decapitalized simple class name when omitted.
+* The same bean name may be declared by more than one `bean(...)` statement — the standard Spring Boot pattern for mutually exclusive variants of one bean, such as the framework's own `grailsUrlConverter` selected by `@ConditionalOnProperty` — provided every declaration with the name carries its own discriminating condition (such as `.annotate(ConditionalOnProperty, ...)`), so that at most one of them registers at runtime. Duplicating a bean name without that is a compile-time error, since Spring would keep the first definition and silently skip the rest.
+* Chaining `.conditionalOnMissingBean(...)` adds a `@ConditionalOnMissingBean` annotation to the generated method, matching Spring Boot's usual back-off semantics. It takes positional types (`.conditionalOnMissingBean(Greeter)`), the annotation's own named attributes (`.conditionalOnMissingBean(name: 'localeResolver', search: SearchStrategy.CURRENT)`), or both. With no arguments at all it compiles to the bare annotation, letting Spring Boot infer the back-off type from the method's return type — the recommended form when a bean simply backs off its own type, since `bean(AvailableLocaleResolver).conditionalOnMissingBean()` already says everything `.conditionalOnMissingBean(AvailableLocaleResolver)` would repeat.
+* Chaining `.conditionalOnMissingBeanName(...)` is the name-based counterpart: "register this bean unless a bean with *this bean's name* already exists". The condition's `name` member is set from the bean's own (explicit or convention-derived) name, so `bean(MessageSource).conditionalOnMissingBeanName(search: SearchStrategy.CURRENT) { ... }` states `messageSource` once and it feeds both `@Bean` and the condition — the two strings the explicit form has to keep in sync cannot diverge. It accepts the annotation's other attributes (`search:`, `ignored:`, ...) but rejects `name:` and types, which would contradict its purpose; use `.conditionalOnMissingBean(...)` for those.
+* Chaining `.primary()`, `.lazy()`, and/or `.scope("name")` adds `@Primary`, `@Lazy`, and `@Scope("name")` respectively.
+* Chaining `.staticMethod()` makes the generated factory method `static` — Spring's recommended shape for `BeanFactoryPostProcessor` and `BeanPostProcessor` beans, which must be creatable without instantiating their declaring configuration class. A static bean's closure cannot reference `field(...)` or `method(...)` members, since those are instance members; under `@CompileStatic` that mistake is a compile error.
+* Chaining `.annotate(AnnotationType[, attr: value, ...])` attaches any other single-valued annotation directly — any `@Conditional*` (built-in or a custom `Condition`), `@Order`, `@DependsOn`, or anything else a hand-written `@Bean` method could carry. It's repeatable, so several different annotations can be chained onto the same bean: `bean('special', Special).annotate(Order, value: 1).annotate(ConditionalOnProperty, prefix: 'myapp', name: 'enabled', havingValue: 'true') { ... }`.
+* Any combination of the above can be chained together, in any order — for example `bean('slowGreeter', SlowGreeter).lazy().scope('prototype') { ... }`.
+* Typed closure parameters (`{ MessageSource messageSource -> ... }`) become the generated method's parameters, so other beans are injected the same way a hand-written `@Bean` method would declare them — and a parameter-level annotation such as `{ @Qualifier('special') Greeter g -> ... }` carries straight through too, since the closure's own parameters become the generated method's parameters directly.
+
+Two more statement kinds can appear inside `beans { }` alongside `bean(...)`, for state and logic shared across bean methods — the same role a hand-written `@Configuration` class's own fields and private methods play:
+
+* `field(["name", ] Type)`, optionally chained with `.value(...)` and/or (repeatably) `.annotate(AnnotationType[, attr: value, ...])`, declares a private field on the generated class. The usual case is injected configuration, and `.value(...)` covers it directly: `field('encoding', String).value('grails.gsp.view.encoding', 'UTF-8')` compiles to `@Value("${grails.gsp.view.encoding:UTF-8}")`. The two-argument form takes a config key and default — and because the DSL builds the placeholder itself, the key may be a bare constant reference (`.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')`), the one shape a directly-written annotation value can't accept. The one-argument form takes a bare config key with no default — `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` — while a string already containing a `${...}` placeholder or a `#{...}` SpEL expression passes through verbatim: `.value('#{T(java.lang.Runtime).getRuntime().availab
leProcessors()}')`.
+* `method(["name", ] Type) { ... }`, chainable with `.annotate(...)` only (`.value(...)` is field-specific), declares a private helper method the same way `bean(...)` declares a public one — typed closure parameters become method parameters, and the closure body becomes the method body.
+
+Both are ordinary private members of the generated class, so a `bean(...)` closure reads a `field(...)` or calls a `method(...)` exactly like a hand-written `@Bean` method would reference a sibling field or method on its own class:
+
+[source,groovy]
+----
+field('suffix', String).value('myapp.greeting-suffix', '!')
+
+method('buildGreeting', String) { String name ->
+ "Hello, ${name}${suffix}"
+}
+
+bean('greeting', Greeting) {
+ new Greeting(buildGreeting('World'))
+}
+----
+
+Because the result is an ordinary `AutoConfiguration` class, it must be registered the same way any Spring Boot auto-configuration is: listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`. Modules built as part of this project can apply the `org.apache.grails.buildsrc.autoconfiguration-imports` Gradle convention plugin to generate that file automatically, by scanning the module's own compiled classes for `@AutoConfiguration` at build time. Projects outside this build register the class the same way any hand-written `AutoConfiguration` is registered — by listing it in that file directly.
+
+NOTE: `@GrailsBeans` does not require extending `Plugin` at all — it produces a plain Spring Boot `AutoConfiguration`, so it can be used by any Spring Boot module, not just a Grails plugin descriptor. Applications can use it too, including directly on the `Application` class — where no imports-file registration is needed, since Spring Boot processes the application class itself — see link:spring.html#springdslAdditional[Configuring Additional Beans]. Within a plugin, reach for it specifically when a bean's registration needs to be ordered against a particular other auto-configuration; otherwise `beanRegistrar()` remains the recommended way to register beans from a `Plugin`.
+
+The DSL still covers a narrower surface than `doWithSpring(BeanBuilder)`:
+
+* Each top-level statement inside `beans { }` must be exactly `bean(...)`, `field(...)`, or `method(...)`, with their respective chaining — an `if`, a `for` loop, or any other imperative Groovy directly inside `beans { }` is a compile-time error, not a runtime one. Note that this is about the DSL's own top-level statements, not the bodies of `bean(...)`/`method(...)` closures themselves, which accept arbitrary Groovy — and `field(...)`/`method(...)` already cover the common reasons to want shared state or logic in the first place.
+* `.annotate(...)` attribute values must be simple compile-time constants (strings, numbers, booleans, class literals, enum constants, or arrays of these) — an annotation attribute that itself takes a nested annotation as a value isn't supported.
+* Dependencies on other beans are expressed only through typed closure parameters (autowired by type), not by name — there is no `ref('beanName')` lookup.
Review Comment:
One more limitation belongs in this list, and it is the one most likely to bite people migrating from `doWithSpring`: a `bean(...)`/`method(...)` closure body is relocated verbatim onto the generated sibling, which is created as `new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)` — it extends `Object` and has no link to the plugin instance.
Verified: the generated class's declared members are the bean methods plus Groovy's own `$staticClassInfo` / `__$stMC` / `metaClass`, its only interface is `GroovyObject`, and its only constructor is a no-arg one — so there is not even a channel through which a `Plugin` reference could arrive. A body reading an inherited `Plugin` member fails accordingly, at context startup:
```
BeanCreationException: Error creating bean with name 'greeting' defined in ProbeAutoConfiguration:
Factory method 'greeting' threw exception with message:
No such property: config for class: ProbeAutoConfiguration
```
`grailsApplication` and `applicationContext` behave identically.
The severity split is worth stating too: under `@CompileStatic` this **is** caught at compile time —
```
[Static type checking] - No such property: config for class: ProbeAutoConfiguration
```
— but only as a side effect of `applyStaticCompilation` copying the annotation onto the sibling. Without `@CompileStatic` there is no diagnostic at all until Spring invokes the factory method during `refresh()`, and the transform has no dedicated validation for it.
Line 198 saying bodies "accept arbitrary Groovy" actively encourages the mistake, and `doWithSpring` closures (which readers are converting *from*) can read plugin state freely. Injected config belongs in `field(...)`, and `GrailsApplication` in a closure parameter — worth saying so explicitly here. A test would help too; the spec currently has no case for a plugin-member reference in a bean body.
##########
settings.gradle:
##########
@@ -107,6 +107,9 @@ def skipMicronautProjects = explicitlySkipMicronaut || (!buildJdkSupportsMicrona
include(
'grails-bootstrap',
+ 'grails-beans-dsl',
+ 'grails-beans-dsl-example',
+ 'grails-beans-dsl-plugin-example',
Review Comment:
These are the only top-level `*-example` modules in the build — every other example in the repository lives under `grails-test-examples/` and is included by the loops further down this file. Was the root placement deliberate? They are plain library modules with Spock tests rather than Grails applications, so `grails-test-examples/` is not an obvious fit either; mostly I want to check it was a decision and not drift.
They are correctly kept out of `publishedProjects`, so nothing ships. Worth noting they are more than samples, though: they are the only consumers of the new `org.apache.grails.buildsrc.autoconfiguration-imports` convention plugin (see my note on `AutoConfigurationImportsPlugin`), and `FarewellGrailsPluginAutoDiscoverySpec` is the only test anywhere that asserts the generated sibling's FQCN. Whatever they are called and wherever they live, that coverage should not be treated as disposable.
##########
grails-core/src/main/groovy/org/grails/compiler/injection/GlobalGrailsClassInjectorTransformation.groovy:
##########
@@ -179,6 +188,44 @@ class GlobalGrailsClassInjectorTransformation implements ASTTransformation, Comp
/**
* @return {@code true} when the {@code grails.isolated.build} system property is {@code true}.
*/
+ /**
+ * Compiles a plugin descriptor's or application class's {@code beans} closure into {@code @Bean}
+ * factory methods, so {@code @GrailsBeans} does not have to be written out - the {@code beans}
+ * property is a convention here in the same way {@code doWithSpring} and {@code watchedResources}
+ * already are.
+ *
+ * <p>The transformation is invoked directly rather than by adding the annotation: annotation-driven
+ * transformations are collected during semantic analysis, so an annotation added at
+ * {@code CANONICALIZATION} would never fire. A class that already declares {@code @GrailsBeans}
+ * is skipped, since its own transformation has run; a class without a {@code beans} property is
+ * skipped too, which is every plugin that does not use the DSL.</p>
+ */
+ private void compileBeansDsl(ClassNode classNode, SourceUnit source) {
+ if (classNode.getProperty(BEANS_PROPERTY) == null) {
+ return
+ }
+ if (!classNode.getAnnotations(GRAILS_BEANS_ANNOTATION).isEmpty()) {
+ return
+ }
+
+ ASTTransformation transformation
+ try {
+ transformation = (ASTTransformation) getClass().classLoader
+ .loadClass('org.grails.compiler.beans.GrailsBeansASTTransformation')
+ .getDeclaredConstructor()
+ .newInstance()
+ }
+ catch (ClassNotFoundException ignored) {
Review Comment:
Two things about the implicit convention are worth pinning down here, since this method is where both land.
**This branch is a silent no-op.** A plugin descriptor or `GrailsAutoConfiguration` subclass declaring `def beans = { bean(...) ... }` without `grails-beans-dsl` on its compile classpath compiles to an ordinary closure-valued property that nothing ever reads: no beans, no warning, no error. It is unreachable inside this build only because `grails-core` exposes the module as `api` (see my note on `grails-core/build.gradle`) — so the silence and that `api` are two halves of one undocumented decision. Narrowing the `api` later makes this a live silent-failure path. At minimum the comment should record *why* the branch is dead rather than only what it does.
**The convention claims any `beans` property, not just DSL-shaped ones.** The only guards are "has a `beans` property" and "does not already declare `@GrailsBeans`". A pre-existing plugin descriptor with an unrelated `def beans = [...]` or `def beans = { ... }` now goes through the transform and fails with `Each 'beans' statement must be a bean(...), field(...), or method(...) call` — a source-incompatible change for third-party plugins, and one the 8.0 upgrade guide does not mention. Worth either narrowing the trigger or calling it out in `upgrading80x.adoc`.
##########
grails-doc/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc:
##########
@@ -119,6 +119,143 @@ class I18nGrailsPlugin extends Plugin {
A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.
+==== Compiling Bean Definitions into a Spring Boot AutoConfiguration
+
+
+`beanRegistrar()` and `doWithSpring` register beans at a single, fixed point in startup: before Spring Boot processes any `{springbootapi}org/springframework/boot/autoconfigure/AutoConfiguration.html[AutoConfiguration]`. That is enough for a bean to win against a Boot default guarded by `@ConditionalOnMissingBean`, but it cannot express ordering *relative to a specific* auto-configuration — running before `WebMvcAutoConfiguration` but after `MessageSourceAutoConfiguration`, say, regardless of where those two land in Boot's overall sort. Only a real `AutoConfiguration` class can declare that ordering, via `@AutoConfiguration(before = ..., after = ...)`.
+
+The link:{api}grails/compiler/beans/GrailsBeans.html[GrailsBeans] annotation lets you author bean definitions with DSL syntax similar to the classic Beans DSL, while compiling them at build time into genuine `@Bean` factory methods on a plain `AutoConfiguration` class — no closures, and nothing DSL-specific, survive into the compiled bytecode. Add `org.apache.grails:grails-beans-dsl` as a dependency and annotate a class whose `beans` property is a closure of `bean(["name", ] Type) { ... }` statements:
+
+[source,groovy]
+----
+import grails.compiler.beans.GrailsBeans
+import org.springframework.boot.autoconfigure.AutoConfiguration
+import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration
+import org.springframework.context.MessageSource
+import org.springframework.context.support.ReloadableResourceBundleMessageSource
+import org.springframework.web.servlet.i18n.CookieLocaleResolver
+import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
+
+@GrailsBeans
+@AutoConfiguration(before = [MessageSourceAutoConfiguration, WebMvcAutoConfiguration])
+class I18nBeans {
+
+ def beans = {
+ bean('messageSource', ReloadableResourceBundleMessageSource) {
+ new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
+ }
+
+ bean('localeResolver', CookieLocaleResolver).conditionalOnMissingBean(CookieLocaleResolver) {
+ new CookieLocaleResolver('locale')
+ }
+
+ bean('localeChangeInterceptor', LocaleChangeInterceptor) { MessageSource messageSource ->
+ new LocaleChangeInterceptor(paramName: 'lang')
+ }
+ }
+}
+----
+
+Each `bean(["name", ] Type)` statement compiles to a public method returning the declared type and annotated `@Bean("name")`. The generated method's name is an implementation detail — Spring resolves the bean by its `@Bean("name")` value, never by the method name. It matches the bean name when that is a valid Java identifier not already taken by an existing member (declared, inherited, or defined elsewhere in the DSL — a bean named `toString` will not override `Object.toString()`); otherwise a synthesized `<type>$N` name (`service$0`, `service$1`, ...) is used instead, so any legal, non-blank Spring bean name compiles:
+
+* The bean name defaults to the decapitalized simple class name when omitted.
+* The same bean name may be declared by more than one `bean(...)` statement — the standard Spring Boot pattern for mutually exclusive variants of one bean, such as the framework's own `grailsUrlConverter` selected by `@ConditionalOnProperty` — provided every declaration with the name carries its own discriminating condition (such as `.annotate(ConditionalOnProperty, ...)`), so that at most one of them registers at runtime. Duplicating a bean name without that is a compile-time error, since Spring would keep the first definition and silently skip the rest.
+* Chaining `.conditionalOnMissingBean(...)` adds a `@ConditionalOnMissingBean` annotation to the generated method, matching Spring Boot's usual back-off semantics. It takes positional types (`.conditionalOnMissingBean(Greeter)`), the annotation's own named attributes (`.conditionalOnMissingBean(name: 'localeResolver', search: SearchStrategy.CURRENT)`), or both. With no arguments at all it compiles to the bare annotation, letting Spring Boot infer the back-off type from the method's return type — the recommended form when a bean simply backs off its own type, since `bean(AvailableLocaleResolver).conditionalOnMissingBean()` already says everything `.conditionalOnMissingBean(AvailableLocaleResolver)` would repeat.
+* Chaining `.conditionalOnMissingBeanName(...)` is the name-based counterpart: "register this bean unless a bean with *this bean's name* already exists". The condition's `name` member is set from the bean's own (explicit or convention-derived) name, so `bean(MessageSource).conditionalOnMissingBeanName(search: SearchStrategy.CURRENT) { ... }` states `messageSource` once and it feeds both `@Bean` and the condition — the two strings the explicit form has to keep in sync cannot diverge. It accepts the annotation's other attributes (`search:`, `ignored:`, ...) but rejects `name:` and types, which would contradict its purpose; use `.conditionalOnMissingBean(...)` for those.
+* Chaining `.primary()`, `.lazy()`, and/or `.scope("name")` adds `@Primary`, `@Lazy`, and `@Scope("name")` respectively.
+* Chaining `.staticMethod()` makes the generated factory method `static` — Spring's recommended shape for `BeanFactoryPostProcessor` and `BeanPostProcessor` beans, which must be creatable without instantiating their declaring configuration class. A static bean's closure cannot reference `field(...)` or `method(...)` members, since those are instance members; under `@CompileStatic` that mistake is a compile error.
+* Chaining `.annotate(AnnotationType[, attr: value, ...])` attaches any other single-valued annotation directly — any `@Conditional*` (built-in or a custom `Condition`), `@Order`, `@DependsOn`, or anything else a hand-written `@Bean` method could carry. It's repeatable, so several different annotations can be chained onto the same bean: `bean('special', Special).annotate(Order, value: 1).annotate(ConditionalOnProperty, prefix: 'myapp', name: 'enabled', havingValue: 'true') { ... }`.
+* Any combination of the above can be chained together, in any order — for example `bean('slowGreeter', SlowGreeter).lazy().scope('prototype') { ... }`.
+* Typed closure parameters (`{ MessageSource messageSource -> ... }`) become the generated method's parameters, so other beans are injected the same way a hand-written `@Bean` method would declare them — and a parameter-level annotation such as `{ @Qualifier('special') Greeter g -> ... }` carries straight through too, since the closure's own parameters become the generated method's parameters directly.
+
+Two more statement kinds can appear inside `beans { }` alongside `bean(...)`, for state and logic shared across bean methods — the same role a hand-written `@Configuration` class's own fields and private methods play:
+
+* `field(["name", ] Type)`, optionally chained with `.value(...)` and/or (repeatably) `.annotate(AnnotationType[, attr: value, ...])`, declares a private field on the generated class. The usual case is injected configuration, and `.value(...)` covers it directly: `field('encoding', String).value('grails.gsp.view.encoding', 'UTF-8')` compiles to `@Value("${grails.gsp.view.encoding:UTF-8}")`. The two-argument form takes a config key and default — and because the DSL builds the placeholder itself, the key may be a bare constant reference (`.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')`), the one shape a directly-written annotation value can't accept. The one-argument form takes a bare config key with no default — `.value('grails.web.linkGenerator.useCache')` compiles to `@Value("${grails.web.linkGenerator.useCache}")` — while a string already containing a `${...}` placeholder or a `#{...}` SpEL expression passes through verbatim: `.value('#{T(java.lang.Runtime).getRuntime().availab
leProcessors()}')`.
Review Comment:
`grails.gsp.view.encoding` does not exist anywhere in Grails — it appears only here and in the new spec fixture. The same sentence then offers `.value(Settings.GSP_VIEW_ENCODING, 'UTF-8')` as the constant form of that key, but that constant is `grails.views.gsp.encoding` (`Settings.groovy:156`), which is what the `GrailsBeans` javadoc and the shipped `I18nGrailsPlugin` conversion both use. Readers copying this get a placeholder that never resolves.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5101315629
## ✅ All tests passed ✅
🏷️ Commit: a70ff87f1f4aac7e542e954e0941dffbcfb905a5
▶️ Tests: 66119 executed
⚪️ Checks: 61/61 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5042899832
## ✅ All tests passed ✅
🏷️ Commit: e4f92b1eab1ba12be5cc2a0eb545b6eadef00ae9
▶️ Tests: 56944 executed
⚪️ Checks: 59/59 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5098173326
## ✅ All tests passed ✅
🏷️ Commit: 1af34ee7f07dd31cfe158db5b64de5d78cac53ba
▶️ Tests: 66045 executed
⚪️ Checks: 61/61 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5125817373
Every review comment above is answered inline, each naming the commit its fix landed in. Four are
departures from what was suggested rather than straight fixes, flagged as such in their threads:
the `isResolved()` guard (a `GroovyBugError` catch instead, since `DecompiledClassNode` reports
itself resolved while having no loaded `Class`), `autoConfigurationName` accepting an FQCN
(documented the four renames instead), `@GrailsBeans` retention (left alone), and
`grails-test-examples/beans-dsl` keeping its own `grails-beans-dsl` declaration (it deliberately has
no `grails-core`).
One change here did **not** come from the review and is worth a look: `d8f2a7b78b` adds a shape to
the DSL. A bean closure with parameters but an **empty body** means "construct the declared type
from these parameters".
```groovy
bean('validateableConstraintsEvaluator', DefaultConstraintEvaluatorFactoryBean).lazy() {
List<MessageSource> messageSources,
@Qualifier('grailsDomainClassMappingContext') MappingContext mappingContext,
GrailsApplication grailsApplication ->
}
```
The parameters stay at the declaration, which is the point — a closure parameter list is the only
place in Groovy that can carry both a generic type and a parameter annotation, so neither
`List<MessageSource>` nor the `@Qualifier` is expressible as an argument anywhere else. The
generated body is the same `new Type(...)` that was written out before, so the compiler selects the
constructor from the parameter types and nothing reads the declared type's constructors — adding one
cannot change what an existing declaration injects.
Five declarations lose a redundant line: the constraint evaluator, the three mail beans and the CORS
filter. Their generated `@Bean` signatures are unchanged, checked with `javap`. A body is still
required wherever construction is more than a pass-through, such as
`new ConfigProperties(grailsApplication.config)` or anything followed by `.tap { }`. The honest cost
is that an empty block reads as a stub at a glance; it is documented in both the guide and the
annotation javadoc.
Two earlier attempts at this are off the branch: both inferred the constructor from the declared
type, which made the declaration silent about what it injects and let a constructor added elsewhere
change or break it.
On verification: `grails.util.GrailsUtilStackFiltererSpec` and
`org.apache.grails.core.GrailsBootstrapRegistryInitializerSpec` fail in `grails-core`. Both
reproduce on a clean `upstream/8.0.x` worktree with none of this branch applied, so they are not
from these changes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3679570876
##########
grails-core/src/main/groovy/org/grails/compiler/injection/GlobalGrailsClassInjectorTransformation.groovy:
##########
@@ -179,6 +188,44 @@ class GlobalGrailsClassInjectorTransformation implements ASTTransformation, Comp
/**
* @return {@code true} when the {@code grails.isolated.build} system property is {@code true}.
*/
+ /**
Review Comment:
Fixed in `94e25dee20`. The `isIsolatedBuild()` block is back on `isIsolatedBuild()`, and `compileBeansDsl` has its own.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3705471675
##########
grails-doc/src/en/guide/conf/applicationClass/applicationLifeCycle.adoc:
##########
@@ -34,3 +34,5 @@ class Application extends GrailsAutoConfiguration {
...
}
----
+
+The `Application` class can also define its beans at compile time instead, by annotating it with `@GrailsBeans` — see link:spring.html#springdslAdditional[Configuring Additional Beans].
Review Comment:
lol, it was... then we decided to add it automatically.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "matrei (via GitHub)" <gi...@apache.org>.
matrei commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3702093276
##########
grails-doc/src/en/guide/conf/applicationClass/applicationLifeCycle.adoc:
##########
@@ -34,3 +34,5 @@ class Application extends GrailsAutoConfiguration {
...
}
----
+
+The `Application` class can also define its beans at compile time instead, by annotating it with `@GrailsBeans` — see link:spring.html#springdslAdditional[Configuring Additional Beans].
Review Comment:
Is the `@GrailsBeans` annotation necessary on the `Application` class?
(I know it isn't)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3679571629
##########
grails-beans-dsl/src/main/java/org/grails/compiler/beans/GrailsBeansASTTransformation.java:
##########
@@ -0,0 +1,1173 @@
+/*
+ * 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.beans;
+
+import java.beans.Introspector;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import groovy.transform.CompilationUnitAware;
+import groovy.transform.CompileStatic;
+import org.apache.groovy.util.BeanUtils;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.ast.expr.MapEntryExpression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.syntax.SyntaxException;
+import org.codehaus.groovy.syntax.Types;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScans;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+import org.springframework.context.annotation.Scope;
+
+/**
+ * Rewrites the {@code beans} closure DSL on a {@link grails.compiler.beans.GrailsBeans}-annotated
+ * class into real {@code @Bean} factory methods, at compile time.
+ *
+ * <p>Recognises three kinds of top-level statement inside the {@code beans} closure:
+ * <ul>
+ * <li>{@code bean(["name", ] Type) { ... }}, optionally chained with any combination of
+ * {@code .conditionalOnMissingBean(...)} (positional types, named annotation attributes, or bare),
+ * {@code .conditionalOnMissingBeanName(...)} (backs off by this bean's own name, set
+ * automatically), {@code .primary()}, {@code .lazy()},
+ * {@code .scope("name")}, {@code .staticMethod()} (a static factory method, for
+ * {@code BeanFactoryPostProcessor}/{@code BeanPostProcessor} beans), and (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Synthesises a public method, returning
+ * the declared type, annotated {@code @org.springframework.context.annotation.Bean("name")} plus
+ * whichever qualifiers were chained, whose body and parameters are lifted directly from the DSL
+ * closure. The generated method's name is an implementation detail: it matches the bean name when
+ * that is a usable Java identifier not already taken by an existing or generated member, and
+ * falls back to a synthesized {@code <type>$N} name otherwise (a non-identifier name like
+ * {@code "my-service"}, a reserved keyword, or a collision - a bean named {@code toString} never
+ * overrides {@code Object.toString()}) - Spring resolves the bean by its {@code @Bean("name")}
+ * value either way, never by the method name. One bean name may be declared by several
+ * {@code bean(...)} statements when every declaration carries its own discriminating condition
+ * (see {@link #validateSharedBeanNames}).</li>
+ * <li>{@code field(["name", ] Type)}, optionally chained with {@code .value(...)} (config
+ * injection: key + default, a bare key, or a verbatim placeholder/SpEL string) and/or (repeatably)
+ * {@code .annotate(AnnotationType[, attr: value, ...])}. Declares a private field on the
+ * generated class, for state shared across bean methods.</li>
+ * <li>{@code method(["name", ] Type) { ... }}, chainable with {@code .annotate(...)} only
+ * ({@code .value(...)} is field-specific).
+ * Declares a private helper method on the generated class, for logic shared across bean methods,
+ * lifted from the DSL closure the same way {@code bean(...)} is.</li>
+ * </ul>
+ *
+ * <p>Fields and helper methods declared this way are ordinary private members of the generated
+ * class - {@code bean(...)} closures reference them the same way a hand-written {@code @Bean}
+ * method would reference a sibling field or method on its {@code @Configuration} class. The
+ * {@code beans} property itself is removed so no closure survives into the compiled class.
+ *
+ * <p>When the annotated class extends {@code grails.plugins.Plugin}, the generated members land
+ * on a new sibling class in the same package instead of on the plugin class itself - named by
+ * swapping a {@code *GrailsPlugin} suffix for {@code AutoConfiguration}, or appending
+ * {@code AutoConfiguration} otherwise. A {@code Plugin} subclass is instantiated by
+ * {@code DefaultGrailsPlugin} via plain reflection, never as a Spring bean, so it cannot carry
+ * {@code @Bean} methods or a meaningful {@code @AutoConfiguration} annotation of its own.
+ * {@code @AutoConfiguration} and every annotation that gates or configures it - the
+ * {@code @Conditional*} family, {@code @Import}/{@code @ImportAutoConfiguration}/
+ * {@code @ImportResource}, {@code @ComponentScan}, {@code @EnableConfigurationProperties},
+ * {@code @PropertySource}/{@code @PropertySources}, and
+ * {@code @AutoConfigureOrder}/{@code Before}/{@code After} - found on the plugin class are moved
+ * onto the generated sibling, since that is the only place any of them has any effect; annotations
+ * outside that set can be named explicitly via {@code @GrailsBeans(moveAnnotations = ...)}. This lets a
+ * plugin author keep bean definitions in the familiar {@code *GrailsPlugin.groovy} file while
+ * everything else about the plugin class - {@code doWithApplicationContext}, {@code onChange},
+ * {@code watchedResources}, etc. - continues to work exactly as it does today.
+ *
+ * <p>{@code @CompileStatic}/{@code @GrailsCompileStatic} on the plugin class is propagated to the
+ * generated sibling. Since the sibling is created after Groovy schedules local annotation
+ * transforms, this transformation invokes Groovy's static-compilation transform directly after
+ * generating the sibling's members. This is the same approach used by other Grails AST transforms
+ * that generate code after local transform discovery.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class GrailsBeansASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private static final String BEANS_PROPERTY = "beans";
+ private static final String BEAN_CALL = "bean";
+ private static final String FIELD_CALL = "field";
+ private static final String METHOD_CALL = "method";
+ private static final Set<String> ROOT_STATEMENT_CALL_NAMES = Set.of(BEAN_CALL, FIELD_CALL, METHOD_CALL);
+ private static final String CONDITIONAL_ON_MISSING_BEAN_CALL = "conditionalOnMissingBean";
+ private static final String CONDITIONAL_ON_MISSING_BEAN_NAME_CALL = "conditionalOnMissingBeanName";
+ private static final String PRIMARY_CALL = "primary";
+ private static final String LAZY_CALL = "lazy";
+ private static final String SCOPE_CALL = "scope";
+ private static final String STATIC_METHOD_CALL = "staticMethod";
+ private static final String ANNOTATE_CALL = "annotate";
+ private static final String VALUE_CALL = "value";
+ private static final Set<String> BEAN_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL);
+ // field(...) and method(...) declare plain class members, not beans - bean-specific
+ // qualifiers don't apply; .value(...) (@Value config injection) is field-only.
+ private static final Set<String> FIELD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL, VALUE_CALL);
+ private static final Set<String> METHOD_QUALIFIER_CALL_NAMES = Set.of(ANNOTATE_CALL);
+ private static final Set<String> ALL_QUALIFIER_CALL_NAMES = Set.of(
+ CONDITIONAL_ON_MISSING_BEAN_CALL, CONDITIONAL_ON_MISSING_BEAN_NAME_CALL,
+ PRIMARY_CALL, LAZY_CALL, SCOPE_CALL, STATIC_METHOD_CALL, ANNOTATE_CALL, VALUE_CALL);
+ private static final String PLUGIN_SUPERCLASS_NAME = "grails.plugins.Plugin";
+ private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
+ private static final String AUTO_CONFIGURATION_SUFFIX = "AutoConfiguration";
+ private static final String AUTO_CONFIGURATION_NAME_MEMBER = "autoConfigurationName";
+ private static final String MOVE_ANNOTATIONS_MEMBER = "moveAnnotations";
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(CompilationUnit compilationUnit) {
+ this.compilationUnit = compilationUnit;
+ }
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ AnnotationNode grailsBeansAnnotation = (AnnotationNode) nodes[0];
+ ClassNode classNode = (ClassNode) nodes[1];
+ PropertyNode beansProperty = classNode.getProperty(BEANS_PROPERTY);
+ if (beansProperty == null) {
+ addError(classNode, source, "@GrailsBeans requires a 'beans' property initialised to a closure");
+ return;
+ }
+
+ Expression initialExpression = beansProperty.getInitialExpression();
+ if (!(initialExpression instanceof ClosureExpression)) {
+ addError(beansProperty, source, "'beans' must be initialised to a closure, e.g. beans = { ... }");
+ return;
+ }
+
+ boolean isPlugin = extendsGrailsPlugin(classNode);
+ if (!isPlugin) {
+ for (String pluginOnlyMember : new String[] { AUTO_CONFIGURATION_NAME_MEMBER, MOVE_ANNOTATIONS_MEMBER }) {
+ if (grailsBeansAnnotation.getMember(pluginOnlyMember) != null) {
+ addError(grailsBeansAnnotation, source, pluginOnlyMember + " has no effect here: it only applies " +
+ "when @GrailsBeans is applied to a grails.plugins.Plugin subclass, where the compiled beans " +
+ "land on a generated sibling class rather than on " + classNode.getNameWithoutPackage() + " itself");
+ }
+ }
+ }
+
+ ClassNode beanMethodHost = isPlugin ?
+ createAutoConfigurationSibling(classNode, grailsBeansAnnotation, source) : classNode;
+
+ Set<String> usedNames = existingMemberNames(beanMethodHost);
+ List<Statement> statements = beanStatements((ClosureExpression) initialExpression);
+ validateSharedBeanNames(statements, source);
+ // Two passes: field(...)/method(...) declare explicit member names, so they are processed
+ // first (along with anything malformed, so every statement is still processed exactly
+ // once) and bean(...) statements second. A bean's derived method name then adapts to every
+ // explicitly-named member wherever it appears in the block - reordering equivalent DSL
+ // statements must never change validity.
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+ for (Statement statement : statements) {
+ if (isBeanRootedStatement(statement)) {
+ processStatement(beanMethodHost, statement, source, usedNames);
+ }
+ }
+
+ if (beanMethodHost != classNode) {
+ applyStaticCompilation(classNode, beanMethodHost, source);
+ }
+
+ classNode.getProperties().remove(beansProperty);
+ classNode.getFields().removeIf(field -> field.getName().equals(BEANS_PROPERTY));
+ }
+
+ private boolean extendsGrailsPlugin(ClassNode classNode) {
+ for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) {
+ if (PLUGIN_SUPERCLASS_NAME.equals(current.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Annotations that only make sense on whatever class Spring Boot actually evaluates as an
+ // auto-configuration - meaningless on a Plugin subclass, which is instantiated by
+ // DefaultGrailsPlugin via plain reflection and never processed by Spring as a bean. Matching
+ // is transitive through meta-annotations (see belongsOnSibling), so this list only needs the
+ // "root" annotations - a composed annotation built on top of any of these (e.g. a custom
+ // @ConditionalOnFeature meta-annotated with Spring Boot's own @ConditionalOnProperty, or a
+ // custom @EnableSomething meta-annotated with @Import) is found automatically.
+ private static final Set<String> SIBLING_ONLY_ANNOTATION_NAMES = Set.of(
+ AutoConfiguration.class.getName(), AutoConfigureOrder.class.getName(),
+ AutoConfigureBefore.class.getName(), AutoConfigureAfter.class.getName(),
+ Import.class.getName(), ImportAutoConfiguration.class.getName(), ImportResource.class.getName(),
+ ComponentScan.class.getName(), ComponentScans.class.getName(),
+ EnableConfigurationProperties.class.getName(),
+ PropertySource.class.getName(), PropertySources.class.getName(),
+ Conditional.class.getName());
+
+ private ClassNode createAutoConfigurationSibling(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ List<AnnotationNode> autoConfigurationAnnotations = pluginClass.getAnnotations(ClassHelper.make(AutoConfiguration.class));
+ if (autoConfigurationAnnotations.isEmpty()) {
+ addError(pluginClass, source, "A Plugin class using @GrailsBeans must also be annotated " +
+ "@AutoConfiguration (even with no before=/after=) - otherwise the generated " +
+ defaultSiblingSimpleName(pluginClass) +
+ " class would never be processed by Spring Boot");
+ }
+
+ String siblingSimpleName = siblingSimpleName(pluginClass, grailsBeansAnnotation, source);
+ String packageName = pluginClass.getPackageName();
+ String siblingName = (packageName == null || packageName.isEmpty()) ?
+ siblingSimpleName : packageName + "." + siblingSimpleName;
+ ClassNode sibling = new ClassNode(siblingName, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
+ source.getAST().addClass(sibling);
+
+ // Matching annotations move entirely rather than being merely copied - they have no effect
+ // where the author wrote them (see SIBLING_ONLY_ANNOTATION_NAMES).
+ Set<String> moveAnnotationNames = parseMoveAnnotations(grailsBeansAnnotation, source);
+ List<AnnotationNode> siblingAnnotations = new ArrayList<>();
+ for (AnnotationNode annotation : pluginClass.getAnnotations()) {
+ if (belongsOnSibling(annotation.getClassNode(), moveAnnotationNames)) {
+ siblingAnnotations.add(annotation);
+ }
+ }
+ sibling.addAnnotations(siblingAnnotations);
+ pluginClass.getAnnotations().removeAll(siblingAnnotations);
+
+ return sibling;
+ }
+
+ private Set<String> parseMoveAnnotations(AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ Expression member = grailsBeansAnnotation.getMember(MOVE_ANNOTATIONS_MEMBER);
+ if (member == null) {
+ return Set.of();
+ }
+ List<Expression> entries = member instanceof ListExpression ?
+ ((ListExpression) member).getExpressions() : List.of(member);
+ Set<String> names = new HashSet<>();
+ for (Expression entry : entries) {
+ if (!(entry instanceof ClassExpression)) {
+ addError(entry, source, "moveAnnotations entries must be annotation class literals, " +
+ "e.g. @GrailsBeans(moveAnnotations = [ComponentScan])");
+ continue;
+ }
+ ClassNode annotationType = ((ClassExpression) entry).getType();
+ if (!annotationType.isAnnotationDefinition()) {
+ addError(entry, source, "\"" + annotationType.getName() + "\" is not an annotation type");
+ continue;
+ }
+ names.add(annotationType.getName());
+ }
+ return names;
+ }
+
+ // A *GrailsPlugin name swaps that suffix for AutoConfiguration (I18nGrailsPlugin ->
+ // I18nAutoConfiguration - the name the hand-written class it replaces would have had);
+ // anything else appends AutoConfiguration.
+ private String defaultSiblingSimpleName(ClassNode pluginClass) {
+ String simpleName = pluginClass.getNameWithoutPackage();
+ if (simpleName.endsWith(GRAILS_PLUGIN_SUFFIX) && simpleName.length() > GRAILS_PLUGIN_SUFFIX.length()) {
+ return simpleName.substring(0, simpleName.length() - GRAILS_PLUGIN_SUFFIX.length()) + AUTO_CONFIGURATION_SUFFIX;
+ }
+ return simpleName + AUTO_CONFIGURATION_SUFFIX;
+ }
+
+ private String siblingSimpleName(ClassNode pluginClass, AnnotationNode grailsBeansAnnotation, SourceUnit source) {
+ String defaultName = defaultSiblingSimpleName(pluginClass);
+ Expression nameArg = grailsBeansAnnotation.getMember(AUTO_CONFIGURATION_NAME_MEMBER);
+ if (nameArg == null) {
+ return defaultName;
+ }
+ Object nameValue = nameArg instanceof ConstantExpression ? ((ConstantExpression) nameArg).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = ...) requires a String literal");
+ return defaultName;
+ }
+ String name = (String) nameValue;
+ if (name.isBlank()) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") must not be " +
+ "blank - omit the attribute entirely to use the default " + defaultName + " instead");
+ return defaultName;
+ }
+ if (!isValidJavaIdentifier(name)) {
+ addError(nameArg, source, "@GrailsBeans(autoConfigurationName = \"" + name + "\") is not a valid " +
+ "name: it becomes the generated sibling's simple class name, so it must be a valid Java identifier");
+ return defaultName;
+ }
+ return name;
+ }
+
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames) {
+ return belongsOnSibling(annotationType, moveAnnotationNames, new HashSet<>());
+ }
+
+ // Recurses through meta-annotations rather than checking only one level, since Spring's own
+ // composed-annotation convention is arbitrarily deep - e.g. a project-specific
+ // @ConditionalOnFeature is typically meta-annotated with an existing @ConditionalOnXxx (itself
+ // meta-annotated @Conditional), not with @Conditional directly. `visited` guards against cycles
+ // and, since every annotation type transitively reaches common JDK meta-annotations
+ // (@Retention, @Target, @Documented) from multiple paths, avoids redundant re-exploration.
+ private boolean belongsOnSibling(ClassNode annotationType, Set<String> moveAnnotationNames, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (SIBLING_ONLY_ANNOTATION_NAMES.contains(annotationType.getName()) ||
+ moveAnnotationNames.contains(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (belongsOnSibling(metaAnnotation.getClassNode(), moveAnnotationNames, visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void applyStaticCompilation(ClassNode pluginClass, ClassNode sibling, SourceUnit source) {
+ List<AnnotationNode> annotations = pluginClass.getAnnotations(ClassHelper.make(CompileStatic.class));
+ if (annotations.isEmpty() || compilationUnit == null) {
+ return;
+ }
+
+ AnnotationNode sourceAnnotation = annotations.get(0);
+ AnnotationNode siblingAnnotation = new AnnotationNode(ClassHelper.make(CompileStatic.class));
+ sourceAnnotation.getMembers().forEach(siblingAnnotation::setMember);
+ sibling.addAnnotation(siblingAnnotation);
+
+ StaticCompileTransformation transformation = new StaticCompileTransformation();
+ transformation.setCompilationUnit(compilationUnit);
+ transformation.visit(new ASTNode[] { siblingAnnotation, sibling }, source);
+ }
+
+ private List<Statement> beanStatements(ClosureExpression dsl) {
+ Statement code = dsl.getCode();
+ if (code instanceof BlockStatement) {
+ return ((BlockStatement) code).getStatements();
+ }
+ List<Statement> single = new ArrayList<>();
+ single.add(code);
+ return single;
+ }
+
+ // Generated names must not collide with anything the host class already has: its own fields
+ // and methods (in the standalone form the host is a real user-written class), every method
+ // inherited through its full type graph - superclasses and interfaces alike, since a bean
+ // named 'toString' or after an interface's default method must synthesize, not override -
+ // and the GroovyObject methods Groovy itself adds at class generation.
+ private Set<String> existingMemberNames(ClassNode host) {
+ Set<String> names = new HashSet<>();
+ for (FieldNode field : host.getFields()) {
+ names.add(field.getName());
+ }
+ Set<String> visited = new HashSet<>();
+ collectMethodNames(host, names, visited);
+ collectMethodNames(ClassHelper.GROOVY_OBJECT_TYPE, names, visited);
+ return names;
+ }
+
+ private void collectMethodNames(ClassNode type, Set<String> names, Set<String> visited) {
+ if (type == null || !visited.add(type.getName())) {
+ return;
+ }
+ for (MethodNode method : type.getMethods()) {
+ names.add(method.getName());
+ }
+ // A Groovy property's accessors are synthesized by the Verifier at class generation, AFTER
+ // this transform runs, so they are not in getMethods() yet - reserve the names they will
+ // occupy, or a same-named bean method would displace the real accessor.
+ for (PropertyNode property : type.getProperties()) {
+ String capitalized = BeanUtils.capitalize(property.getName());
+ names.add("get" + capitalized);
+ names.add("set" + capitalized);
+ if (ClassHelper.boolean_TYPE.equals(property.getType()) ||
+ ClassHelper.Boolean_TYPE.equals(property.getType())) {
+ names.add("is" + capitalized);
+ }
+ }
+ collectMethodNames(type.getSuperClass(), names, visited);
+ for (ClassNode implemented : type.getInterfaces()) {
+ collectMethodNames(implemented, names, visited);
+ }
+ }
+
+ // Silent classification counterpart of processStatement's qualifier-chain walk: descends to
+ // the root call without reporting anything, so malformed statements are classified (not
+ // validated) here and still produce their usual errors when actually processed.
+ private boolean isBeanRootedStatement(Statement statement) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ return false;
+ }
+ MethodCallExpression call = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(call.getMethodAsString()) &&
+ call.getObjectExpression() instanceof MethodCallExpression) {
+ call = (MethodCallExpression) call.getObjectExpression();
+ }
+ return BEAN_CALL.equals(call.getMethodAsString());
+ }
+
+ // A Spring bean name may be declared by more than one bean(...) statement - the standard
+ // autoconfiguration pattern for mutually exclusive variants of one bean, e.g. Grails' two
+ // "grailsUrlConverter" beans selected by @ConditionalOnProperty - but only when every
+ // statement sharing the name carries a condition of its own that could discriminate between
+ // them at runtime. Without one, the duplicates can never all take effect (Spring keeps the
+ // first definition from a configuration class and silently skips the rest), so the likeliest
+ // explanation is a copy-paste accident - rejected at compile time instead. The shared-name
+ // back-off (.conditionalOnMissingBeanName(), or .conditionalOnMissingBean() with no
+ // arguments) does not count: it is identical on every duplicate by construction, so it can
+ // never tell them apart.
+ private void validateSharedBeanNames(List<Statement> statements, SourceUnit source) {
+ Map<String, List<BeanNameUse>> usesByName = new LinkedHashMap<>();
+ for (Statement statement : statements) {
+ if (!isBeanRootedStatement(statement)) {
+ continue;
+ }
+ BeanNameUse use = parseBeanNameUse(
+ (MethodCallExpression) ((ExpressionStatement) statement).getExpression());
+ if (use != null) {
+ usesByName.computeIfAbsent(use.beanName, key -> new ArrayList<>()).add(use);
+ }
+ }
+ for (List<BeanNameUse> uses : usesByName.values()) {
+ if (uses.size() < 2) {
+ continue;
+ }
+ for (BeanNameUse use : uses) {
+ if (!use.conditioned) {
+ addError(use.baseCall, source, "\"" + use.beanName + "\" is already used as the Spring " +
+ "bean name of another bean(...) statement - declaring it more than once is only " +
+ "allowed when every declaration with the name carries its own discriminating " +
+ "condition (e.g. .annotate(ConditionalOnProperty, ...)), so that at most one of " +
+ "them registers at runtime");
+ }
+ }
+ }
+ }
+
+ private static final class BeanNameUse {
+ private final String beanName;
+ private final MethodCallExpression baseCall;
+ private final boolean conditioned;
+
+ BeanNameUse(String beanName, MethodCallExpression baseCall, boolean conditioned) {
+ this.beanName = beanName;
+ this.baseCall = baseCall;
+ this.conditioned = conditioned;
+ }
+ }
+
+ // Silent classification counterpart of processBeanStatement's parsing, in the same spirit as
+ // isBeanRootedStatement: extracts the bean name and whether the statement carries a
+ // discriminating condition, returning null for anything malformed - a malformed statement
+ // still produces its usual errors when actually processed.
+ private BeanNameUse parseBeanNameUse(MethodCallExpression outerCall) {
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ return null;
+ }
+ qualifierCalls.add(baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+ if (!BEAN_CALL.equals(baseCall.getMethodAsString())) {
+ return null;
+ }
+
+ List<Expression> args = withoutTrailingClosure(flatten(baseCall.getArguments()), baseCall, outerCall);
+ if (args.isEmpty() || args.size() > 2 || !(args.get(args.size() - 1) instanceof ClassExpression)) {
+ return null;
+ }
+ String name;
+ if (args.size() == 1) {
+ name = decapitalize(((ClassExpression) args.get(0)).getType().getNameWithoutPackage());
+ }
+ else {
+ Object nameValue = args.get(0) instanceof ConstantExpression ?
+ ((ConstantExpression) args.get(0)).getValue() : null;
+ if (!(nameValue instanceof String)) {
+ return null;
+ }
+ name = (String) nameValue;
+ }
+ return new BeanNameUse(name, baseCall, hasDiscriminatingCondition(qualifierCalls, outerCall));
+ }
+
+ private boolean hasDiscriminatingCondition(List<MethodCallExpression> qualifierCalls, MethodCallExpression outerCall) {
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ List<Expression> args = withoutTrailingClosure(flatten(qualifierCall.getArguments()), qualifierCall, outerCall);
+ if (CONDITIONAL_ON_MISSING_BEAN_CALL.equals(qualifierName) && !args.isEmpty()) {
+ return true;
+ }
+ if (ANNOTATE_CALL.equals(qualifierName)) {
+ for (Expression arg : args) {
+ if (arg instanceof ClassExpression && isConditionalAnnotation(((ClassExpression) arg).getType())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private List<Expression> withoutTrailingClosure(List<Expression> args, MethodCallExpression call,
+ MethodCallExpression outerCall) {
+ if (call == outerCall && !args.isEmpty() && args.get(args.size() - 1) instanceof ClosureExpression) {
+ return args.subList(0, args.size() - 1);
+ }
+ return args;
+ }
+
+ private boolean isConditionalAnnotation(ClassNode annotationType) {
+ return isConditionalAnnotation(annotationType, new HashSet<>());
+ }
+
+ // The same transitive meta-annotation walk belongsOnSibling does, against @Conditional alone:
+ // every @ConditionalOnXxx - Spring Boot's own and arbitrarily-deeply composed custom ones -
+ // eventually reaches @Conditional through its meta-annotations.
+ private boolean isConditionalAnnotation(ClassNode annotationType, Set<String> visited) {
+ if (!visited.add(annotationType.getName())) {
+ return false;
+ }
+ if (Conditional.class.getName().equals(annotationType.getName())) {
+ return true;
+ }
+ for (AnnotationNode metaAnnotation : annotationType.getAnnotations()) {
+ if (isConditionalAnnotation(metaAnnotation.getClassNode(), visited)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void processStatement(ClassNode classNode, Statement statement, SourceUnit source, Set<String> usedNames) {
+ if (!(statement instanceof ExpressionStatement) ||
+ !(((ExpressionStatement) statement).getExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Each 'beans' statement must be a bean(...), field(...), or method(...) call");
+ return;
+ }
+
+ MethodCallExpression outerCall = (MethodCallExpression) ((ExpressionStatement) statement).getExpression();
+
+ // Walk from the outermost (last-written) call back to the bean(...)/field(...)/method(...)
+ // call at the root, collecting any chained qualifiers along the way.
+ List<MethodCallExpression> qualifierCalls = new ArrayList<>();
+ MethodCallExpression baseCall = outerCall;
+ while (!ROOT_STATEMENT_CALL_NAMES.contains(baseCall.getMethodAsString())) {
+ if (!ALL_QUALIFIER_CALL_NAMES.contains(baseCall.getMethodAsString()) ||
+ !(baseCall.getObjectExpression() instanceof MethodCallExpression)) {
+ addError(statement, source, "Expected bean([\"name\", ] Type) { ... }, field([\"name\", ] Type), " +
+ "or method([\"name\", ] Type) { ... }, optionally chained with qualifiers");
+ return;
+ }
+ qualifierCalls.add(0, baseCall);
+ baseCall = (MethodCallExpression) baseCall.getObjectExpression();
+ }
+
+ String rootName = baseCall.getMethodAsString();
+ boolean isBean = BEAN_CALL.equals(rootName);
+ Set<String> allowedQualifiers = isBean ? BEAN_QUALIFIER_CALL_NAMES :
+ FIELD_CALL.equals(rootName) ? FIELD_QUALIFIER_CALL_NAMES : METHOD_QUALIFIER_CALL_NAMES;
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ if (!allowedQualifiers.contains(qualifierCall.getMethodAsString())) {
+ addError(qualifierCall, source, "." + qualifierCall.getMethodAsString() + "(...) cannot be " +
+ "chained onto " + rootName + "(...)");
+ return;
+ }
+ }
+
+ // .annotate(...) is repeatable (once per distinct annotation type, enforced when the
+ // annotation is actually attached below); every other qualifier is single-use.
+ Set<String> seenQualifiers = new HashSet<>();
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ String qualifierName = qualifierCall.getMethodAsString();
+ if (!ANNOTATE_CALL.equals(qualifierName) && !seenQualifiers.add(qualifierName)) {
+ addError(qualifierCall, source, "." + qualifierName + "(...) may only be chained once per " +
+ rootName + "(...)");
+ return;
+ }
+ }
+
+ if (isBean) {
+ processBeanStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ else if (FIELD_CALL.equals(rootName)) {
+ processFieldStatement(classNode, baseCall, qualifierCalls, source, usedNames);
+ }
+ else {
+ processMethodStatement(classNode, outerCall, baseCall, qualifierCalls, source, usedNames);
+ }
+ }
+
+ private boolean registerName(String name, ASTNode location, SourceUnit source, Set<String> usedNames, String errorSuffix) {
+ if (!usedNames.add(name)) {
+ addError(location, source, "\"" + name + "\" " + errorSuffix);
+ return false;
+ }
+ return true;
+ }
+
+ private void processBeanStatement(ClassNode classNode, MethodCallExpression outerCall, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> closureCallArgs = flatten(outerCall.getArguments());
+ if (closureCallArgs.isEmpty() || !(closureCallArgs.get(closureCallArgs.size() - 1) instanceof ClosureExpression)) {
+ addError(outerCall, source, "bean(...) must end with a factory closure: bean(Type) { ... }");
+ return;
+ }
+ ClosureExpression factory = (ClosureExpression) closureCallArgs.get(closureCallArgs.size() - 1);
+
+ // When bean(...) is itself the outermost call (no qualifiers chained), it carries the
+ // trailing closure as its own last argument - exclude it before validating the [name, ] Type
+ // shape, since it was already validated above.
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ if (baseCall == outerCall && !baseArgs.isEmpty()) {
+ baseArgs = baseArgs.subList(0, baseArgs.size() - 1);
+ }
+
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, BEAN_CALL, false);
+ if (typeAndName == null) {
+ return;
+ }
+
+ // The method name is an implementation detail - Spring resolves the bean by its
+ // @Bean("name") value, never by the factory method's name - so a bean name that isn't a
+ // usable Java identifier, or is already taken by an existing member, synthesizes instead
+ // of erroring.
+ String javaMethodName = isValidJavaIdentifier(typeAndName.name) && !usedNames.contains(typeAndName.name) ?
+ typeAndName.name :
+ syntheticBeanMethodName(typeAndName.type.getType(), usedNames);
+ usedNames.add(javaMethodName);
+
+ MethodNode beanMethod = new MethodNode(
+ javaMethodName,
+ Modifier.PUBLIC,
+ typeAndName.type.getType(),
+ factory.getParameters() == null ? Parameter.EMPTY_ARRAY : factory.getParameters(),
+ ClassNode.EMPTY_ARRAY,
+ factory.getCode());
+ beanMethod.addAnnotation(beanAnnotation(typeAndName.name));
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (qualifierCall == outerCall) {
+ // only the outermost call in the chain can carry the trailing factory closure
+ qualifierArgs = qualifierArgs.subList(0, qualifierArgs.size() - 1);
+ }
+ if (!applyQualifier(beanMethod, typeAndName.name, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+
+ classNode.addMethod(beanMethod);
+ }
+
+ private String syntheticBeanMethodName(ClassNode beanType, Set<String> usedNames) {
+ String base = decapitalize(beanType.getNameWithoutPackage());
+ String candidate;
+ int index = 0;
+ do {
+ candidate = base + "$" + index;
+ index++;
+ }
+ while (usedNames.contains(candidate));
+ return candidate;
+ }
+
+ private void processFieldStatement(ClassNode classNode, MethodCallExpression baseCall,
+ List<MethodCallExpression> qualifierCalls, SourceUnit source, Set<String> usedNames) {
+ List<Expression> baseArgs = flatten(baseCall.getArguments());
+ TypeAndName typeAndName = parseNameAndType(baseArgs, baseCall, source, FIELD_CALL, true);
+ if (typeAndName == null) {
+ return;
+ }
+ if (!registerName(typeAndName.name, baseCall, source, usedNames,
+ "is already used by another member of the class (declared, inherited, or another field(...)/method(...) statement) - " +
+ "generated member names must be unique")) {
+ return;
+ }
+
+ FieldNode field = classNode.addField(typeAndName.name, Modifier.PRIVATE, typeAndName.type.getType(), null);
+
+ for (MethodCallExpression qualifierCall : qualifierCalls) {
+ List<Expression> qualifierArgs = flatten(qualifierCall.getArguments());
+ if (VALUE_CALL.equals(qualifierCall.getMethodAsString())) {
+ AnnotationNode valueAnnotation = valueAnnotation(qualifierArgs, qualifierCall, source);
+ if (valueAnnotation == null || !addAnnotationIfAbsent(field, qualifierCall, valueAnnotation, source)) {
+ return;
+ }
+ }
+ else if (!applyGenericAnnotation(field, qualifierCall, qualifierArgs, source)) {
+ return;
+ }
+ }
+ }
+
+ // .value(key, default) builds the '${key:default}' placeholder itself, as a concatenation the
+ // compiler folds into a constant - which is what lets the key be a bare static-final constant
+ // reference, the one shape a directly-written annotation value rejects. .value(single) is a
+ // bare config key with no default, auto-wrapped into '${key}' - injecting the key's literal
+ // text is never what .value(...) is for - unless the string already contains a '${'
+ // placeholder or '#{' SpEL expression, which passes through verbatim (including mixed
+ // literals like 'http://${app.host}/'). A genuine literal stays expressible via
+ // .annotate(Value, value: ...).
+ private AnnotationNode valueAnnotation(List<Expression> args, MethodCallExpression qualifierCall, SourceUnit source) {
+ if (args.isEmpty() || args.size() > 2) {
+ addError(qualifierCall, source, ".value(...) requires a config key and default - e.g. " +
+ ".value(Settings.GSP_VIEW_ENCODING, \"UTF-8\") - or a single config key/placeholder/SpEL string");
+ return null;
+ }
+ // The pieces are resolved and folded HERE, into a plain constant, rather than being left
+ // as a concatenation for Groovy's own annotation folding: under @CompileStatic the static
+ // compiler rewrites '+' into .plus() calls before that folding runs, which would reject
+ // the member as a non-constant.
+ String memberValue;
+ if (args.size() == 1) {
+ String placeholder = resolveStringConstant(args.get(0));
+ if (placeholder == null) {
+ addError(args.get(0), source, ".value(...) arguments must be compile-time String constants " +
+ "(a literal, a static final constant reference, or a concatenation of those)");
+ return null;
+ }
+ if (placeholder.isBlank()) {
+ addError(args.get(0), source, ".value(...) requires a non-blank config key - a blank one " +
+ "would compile to the unresolvable placeholder ${}");
+ return null;
+ }
+ memberValue = placeholder.contains("${") || placeholder.contains("#{") ?
+ placeholder : "${" + placeholder + "}";
+ }
+ else {
+ String key = resolveStringConstant(args.get(0));
+ String defaultValue = resolveStringConstant(args.get(1));
+ if (key == null || defaultValue == null) {
+ addError(key == null ? args.get(0) : args.get(1), source, ".value(...) arguments must be " +
+ "compile-time String constants (a literal, a static final constant reference, or a " +
+ "concatenation of those)");
+ return null;
+ }
+ // Only the KEY must be non-blank: a deliberately blank default ('${key:}') is legal
+ // and used (e.g. grails.i18n.default.locale falls back to the JVM default locale).
+ if (key.isBlank()) {
+ addError(args.get(0), source, ".value(key, default) requires a non-blank config key - " +
+ "only the default may be blank");
+ return null;
+ }
+ memberValue = "${" + key + ":" + defaultValue + "}";
+ }
+ AnnotationNode annotation = new AnnotationNode(ClassHelper.make(Value.class));
+ annotation.setMember("value", new ConstantExpression(memberValue));
+ return annotation;
+ }
+
+ // Resolves an expression to its compile-time String value: literals directly; a static final
+ // constant reference either from its AST initial expression (a constant declared in the same
+ // compilation unit) or reflectively from the already-compiled class on the classpath; and
+ // concatenations of resolvable pieces recursively.
+ private String resolveStringConstant(Expression expression) {
+ if (expression instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) expression).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ if (expression instanceof BinaryExpression) {
+ BinaryExpression binary = (BinaryExpression) expression;
+ if (binary.getOperation().getType() != Types.PLUS) {
+ return null;
+ }
+ String left = resolveStringConstant(binary.getLeftExpression());
+ String right = resolveStringConstant(binary.getRightExpression());
+ return left != null && right != null ? left + right : null;
+ }
+ if (expression instanceof PropertyExpression) {
+ PropertyExpression property = (PropertyExpression) expression;
+ if (!(property.getObjectExpression() instanceof ClassExpression)) {
+ return null;
+ }
+ ClassNode owner = property.getObjectExpression().getType();
+ String fieldName = property.getPropertyAsString();
+ if (fieldName == null) {
+ return null;
+ }
+ FieldNode field = owner.getField(fieldName);
+ if (field != null && field.isStatic() && field.isFinal() &&
+ field.getInitialExpression() instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) field.getInitialExpression()).getValue();
+ return value instanceof String ? (String) value : null;
+ }
+ try {
+ Object value = owner.getTypeClass().getField(fieldName).get(null);
Review Comment:
Fixed in `9743d3a54e`.
The AST lookup now walks interfaces (`findStaticFinalField`), so an interface-declared constant — the shape every `grails.config.Settings` key has — resolves while its owner is still compiling.
I did not add `owner.isResolved()`: `DecompiledClassNode`, which is what the compiler hands you for a class read from a jar, reports itself resolved while still having no loaded `Class`, so the guard alone would not close the hole. The catch includes `GroovyBugError` instead, which covers every node kind. Say if you would rather see `isResolved()` on top of it.
Two tests: a constant inherited through two same-unit interfaces resolves, and a typo against a same-file constant produces the located message rather than `BUG! exception in phase 'canonicalization'`.
##########
grails-beans-dsl-plugin-example/src/main/groovy/beandsl/example/plugin/GreetingGrailsPlugin.groovy:
##########
@@ -0,0 +1,52 @@
+/*
+ * 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 beandsl.example.plugin
+
+import org.springframework.beans.factory.annotation.Value
+import org.springframework.boot.autoconfigure.AutoConfiguration
+
+import grails.compiler.beans.GrailsBeans
+import grails.plugins.Plugin
+
+/**
+ * Demonstrates {@code field(...)} and {@code method(...)} - the same shape real autoconfigurations
+ * like the built-in i18n plugin's need: injected configuration shared across beans, and a private
+ * helper factored out of a bean's construction logic. Both compile onto the generated
+ * {@code GreetingGrailsPluginAutoConfiguration} sibling as ordinary private members, exactly like
Review Comment:
Fixed in `af64be699c` — the suffix is replaced, so it is `GreetingAutoConfiguration`.
The Greeting spec now asserts the FQCN the way the Farewell one does, plus that the `field(...)` and `method(...)` members landed on the sibling rather than the plugin class.
##########
settings.gradle:
##########
@@ -107,6 +107,9 @@ def skipMicronautProjects = explicitlySkipMicronaut || (!buildJdkSupportsMicrona
include(
'grails-bootstrap',
+ 'grails-beans-dsl',
+ 'grails-beans-dsl-example',
+ 'grails-beans-dsl-plugin-example',
Review Comment:
Not deliberate. Both moved under `grails-test-examples/` in `0224df0ecd`, per the table in your later comment.
All 7 specs run and pass at the new locations, `FarewellGrailsPluginAutoDiscoverySpec` included. Since that one now sits outside core-only CI, `grails-databinding` applies the `autoconfiguration-imports` plugin so it has a consumer there too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5094209109
The `grails-core` conversion (6986f0cc12, with the follow-up fix in 100b9dbf77), same pattern. This is the first one where the plugin keeps its legacy `doWithSpring()` — the bean builder closure is isolated with `@CompileDynamic` so the class itself can carry `@CompileStatic`, which the transform copies onto the generated sibling — and the first where the sibling does not land on the deleted class's exact package. Imports and comments are trimmed here; each linked filename is the verbatim, commit-pinned source.
Before, [`CoreAutoConfiguration.java`](https://github.com/codeconsole/grails-core/blob/5c71d9e88ceae522071f724681b5de2baafdb43a/grails-core/src/main/groovy/org/grails/plugins/core/CoreAutoConfiguration.java#L41-L69) (since deleted):
```java
@AutoConfiguration(before = { PropertyPlaceholderAutoConfiguration.class })
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class CoreAutoConfiguration {
@Value("${" + Settings.SPRING_PLACEHOLDER_PREFIX + ":#{null}}")
private String placeholderPrefix;
@Bean
@Primary
public ClassLoader classLoader(GrailsApplication grailsApplication) {
return grailsApplication.getClassLoader();
}
@Bean
@Primary
public ConfigProperties grailsConfigProperties(GrailsApplication grailsApplication) {
return new ConfigProperties(grailsApplication.getConfig());
}
@Bean
@Primary
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
GrailsPlaceholderConfigurer grailsPlaceholderConfigurer = new GrailsPlaceholderConfigurer();
if (placeholderPrefix != null) {
grailsPlaceholderConfigurer.setPlaceholderPrefix(placeholderPrefix);
}
return grailsPlaceholderConfigurer;
}
}
```
After — [`CoreGrailsPlugin.groovy`](https://github.com/codeconsole/grails-core/blob/100b9dbf77d65a32cef2f1698113052fa9f59ac7/grails-core/src/main/groovy/org/grails/plugins/CoreGrailsPlugin.groovy#L67-L103)'s class declaration and `beans` block (the plugin's metadata properties between them are elided below, unchanged by the conversion; `doWithSpring()` and `onChange()` further down the file are pre-existing plugin logic, untouched):
```groovy
@CompileStatic
@GrailsBeans
@AutoConfiguration(before = [PropertyPlaceholderAutoConfiguration])
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
class CoreGrailsPlugin extends Plugin {
// ... pre-existing plugin metadata properties, unchanged ...
def beans = {
bean('classLoader', ClassLoader).primary() { GrailsApplication grailsApplication ->
grailsApplication.classLoader
}
bean('grailsConfigProperties', ConfigProperties).primary() { GrailsApplication grailsApplication ->
new ConfigProperties(grailsApplication.config)
}
bean('propertySourcesPlaceholderConfigurer', PropertySourcesPlaceholderConfigurer).primary().staticMethod() { Environment environment ->
def configurer = new GrailsPlaceholderConfigurer()
String prefix = environment.getProperty(Settings.SPRING_PLACEHOLDER_PREFIX)
if (prefix != null) {
configurer.placeholderPrefix = prefix
}
configurer
}
}
```
`CoreGrailsPlugin` lives in `org.grails.plugins` while the deleted class was in `org.grails.plugins.core`, and the sibling is always emitted into the plugin's own package, so the class becomes `org.grails.plugins.CoreAutoConfiguration` and the single hand-maintained `AutoConfiguration.imports` entry moves with it. Nothing else in the repository referenced the old package, and the `org.grails` prefix filter in `grails-testing-support-core` still matches. `@AutoConfiguration(before = ...)` and `@AutoConfigureOrder` move onto the sibling at compile time, and javap confirms the rest is equivalent to the deleted Java class: the same three method signatures, the same `@Bean`/`@Primary` pairs, and no `invokedynamic` call sites, with the `beans` closure not surviving on the plugin class.
The `.staticMethod()` on the placeholder configurer is a behaviour fix rather than a like-for-like port, and it is worth calling out because the DSL made it visible. `grails.spring.placeholder.prefix` never had any effect: the configurer is a `BeanFactoryPostProcessor`, so its configuration class is instantiated during `invokeBeanFactoryPostProcessors`, before `AutowiredAnnotationBeanPostProcessor` is registered, and the `@Value` field the original instance method read was therefore always `null` — confirmed by reflection against a refreshed context, where the field held `null` and the configurer kept the default `${` prefix. A `static` factory method needs no enclosing instance and can take the `Environment` directly, which is the shape Boot's own `PropertyPlaceholderAutoConfiguration` uses, so the configured prefix now actually applies.
The auto-configuration previously had no test coverage at all; the new `CoreAutoConfigurationSpec` asserts the three beans and their types, the class loader identity, `@Primary` winning against a competing `ClassLoader` candidate, the config properties read-through to the application config, Boot's `PropertyPlaceholderAutoConfiguration` ordering after this one and backing off, default-prefix placeholder resolution in bean definitions, an unresolvable placeholder being left in place rather than failing the context, and — newly possible — a configured prefix both resolving `@{foo.bar}` and displacing the default so `${foo.bar}` is left literal. One dependency note for anyone writing similar specs: `spring-boot-test` alone is not enough, because `ApplicationContextRunner`'s signatures reach AssertJ through `ApplicationContextAssertProvider`; without `assertj-core` on the test classpath Groovy cannot introspect the runner at all — its metaclass degrades to `Object`'s methods and
every call fails to dispatch with `MissingMethodException`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5053346316
## ✅ All tests passed ✅
🏷️ Commit: 98b046b946ff3b732abb76e32ae36edbe85021a1
▶️ Tests: 35985 executed
⚪️ Checks: 59/59 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3671179734
##########
grails-core/build.gradle:
##########
@@ -51,6 +51,8 @@ dependencies {
api 'jakarta.persistence:jakarta.persistence-api'
api 'jakarta.annotation:jakarta.annotation-api'
+ api project(':grails-beans-dsl')
Review Comment:
Correcting my earlier comment on this line: this `api` is right, and it should stay.
`grails-core` is on every Grails project's classpath, so declaring the beans DSL as `api` here is precisely how it should reach downstream projects — the same thing `grails-core` already does for several other modules. The DSL is effectively part of that default surface rather than an optional extra, and `GlobalGrailsClassInjectorTransformation.compileBeansDsl` depends on exactly that to make the implicit `def beans = { }` convention work for third-party plugin authors.
What follows from it is that **no other module needs to declare `grails-beans-dsl` at all**. I've left a note on each of the seven that currently does. My previous comment asked for the nine declarations to "agree on one story" — the story is this line, and the other seven should be deleted.
##########
grails-cache/build.gradle:
##########
@@ -49,6 +49,7 @@ dependencies {
api "org.codehaus.gpars:gpars:$gparsVersion"
api "com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:$concurrentlinkedhashmapLruVersion"
+ implementation project(':grails-beans-dsl')
Review Comment:
Drop this line — `grails-core` declares `api project(':grails-beans-dsl')`, so the DSL is already on this module's compile classpath. See my note on `grails-core/build.gradle:54`.
##########
grails-i18n/build.gradle:
##########
@@ -41,6 +41,8 @@ dependencies {
api project(':grails-web-core')
api 'org.apache.groovy:groovy'
+ implementation project(':grails-beans-dsl')
Review Comment:
Drop this line — `grails-core` declares `api project(':grails-beans-dsl')`, so the DSL is already on this module's compile classpath. See my note on `grails-core/build.gradle:54`.
##########
grails-domain-class/build.gradle:
##########
@@ -38,6 +38,7 @@ dependencies {
implementation platform(project(':grails-bom'))
+ implementation project(':grails-beans-dsl')
Review Comment:
Drop this line — `grails-core` declares `api project(':grails-beans-dsl')`, so the DSL is already on this module's compile classpath. See my note on `grails-core/build.gradle:54`.
##########
grails-url-mappings/build.gradle:
##########
@@ -43,6 +43,8 @@ dependencies {
api 'org.apache.groovy:groovy'
api 'org.springframework.boot:spring-boot-servlet'
+ implementation project(':grails-beans-dsl')
Review Comment:
Drop this line — `grails-core` declares `api project(':grails-beans-dsl')`, so the DSL is already on this module's compile classpath. See my note on `grails-core/build.gradle:54`.
##########
grails-beans-dsl-plugin-example/build.gradle:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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 'groovy'
+ id 'java-library'
+ 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.buildsrc.autoconfiguration-imports'
+ id 'org.apache.grails.gradle.grails-code-style'
+ id 'org.apache.grails.gradle.grails-jacoco'
+}
+
+version = projectVersion
+group = 'org.apache.grails'
Review Comment:
Alongside the directory move (see my note on `settings.gradle`), this file needs to adopt the `grails-test-examples` conventions:
* `group = 'examples'` — no module under `grails-test-examples/` uses `org.apache.grails`; that group is for published framework modules, and these aren't published.
* Swap `gradle/test-config.gradle` for `gradle/functional-test-config.gradle`, and add `testRuntimeOnly 'org.junit.platform:junit-platform-launcher'` since the latter doesn't supply it.
* Drop `implementation project(':grails-beans-dsl')` — `grails-core`'s `api` covers it.
* Drop `org.apache.grails.gradle.grails-code-style` and `org.apache.grails.gradle.grails-jacoco`: no other module in that directory applies either, and keeping them would put example code into the violation and coverage reports. Happy to be overruled if that's intentional, but it should be a deliberate precedent rather than a carry-over.
* Keep `groovy`/`java-library` and `org.apache.grails.buildsrc.autoconfiguration-imports` — the latter is the point of the module and is entirely path-independent, so the move doesn't affect it.
Also worth updating the comment at line 41, which refers to the sibling by its current name.
##########
grails-beans-dsl-example/build.gradle:
##########
@@ -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.
+ */
+
+plugins {
+ id 'groovy'
+ id 'java-library'
+ 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.buildsrc.autoconfiguration-imports'
+ id 'org.apache.grails.gradle.grails-code-style'
+ id 'org.apache.grails.gradle.grails-jacoco'
+}
+
+version = projectVersion
+group = 'org.apache.grails'
Review Comment:
Alongside the directory move (see my note on `settings.gradle`), this file needs to adopt the `grails-test-examples` conventions:
* `group = 'examples'` — no module under `grails-test-examples/` uses `org.apache.grails`; that group is for published framework modules, and these aren't published.
* Swap `gradle/test-config.gradle` for `gradle/functional-test-config.gradle`, and add `testRuntimeOnly 'org.junit.platform:junit-platform-launcher'` since the latter doesn't supply it.
* Drop `implementation project(':grails-beans-dsl')` — `grails-core`'s `api` covers it.
* Drop `org.apache.grails.gradle.grails-code-style` and `org.apache.grails.gradle.grails-jacoco`: no other module in that directory applies either, and keeping them would put example code into the violation and coverage reports. Happy to be overruled if that's intentional, but it should be a deliberate precedent rather than a carry-over.
* Keep `groovy`/`java-library` and `org.apache.grails.buildsrc.autoconfiguration-imports` — the latter is the point of the module and is entirely path-independent, so the move doesn't affect it.
##########
grails-databinding/build.gradle:
##########
@@ -38,6 +38,7 @@ dependencies {
implementation platform(project(':grails-bom'))
+ implementation project(':grails-beans-dsl')
Review Comment:
Drop this line — `grails-core` declares `api project(':grails-beans-dsl')`, so the DSL is already on this module's compile classpath. See my note on `grails-core/build.gradle:54`.
##########
grails-gsp/grails-sitemesh3/build.gradle:
##########
@@ -52,6 +52,7 @@ dependencies {
api project(':grails-core')
implementation 'org.apache.groovy:groovy'
+ implementation project(':grails-beans-dsl')
Review Comment:
Drop this line — `grails-core` declares `api project(':grails-beans-dsl')`, so the DSL is already on this module's compile classpath. See my note on `grails-core/build.gradle:54`.
##########
grails-mail/build.gradle:
##########
@@ -76,10 +76,14 @@ dependencies {
compileOnly 'org.springframework.boot:spring-boot-autoconfigure' // @AutoConfiguration, @ConditionalOnProperty, @ConfigurationProperties
compileOnly 'org.apache.groovy:groovy' // Provided as this is a Grails plugin
compileOnly 'org.slf4j:slf4j-api' // @Slf4j
+ compileOnly project(':grails-beans-dsl') // comp: @GrailsBeans
Review Comment:
Drop this line too. `compileOnly` was the closest to correct of the three scopes in use, but it is still unnecessary — `grails-core` declares `api project(':grails-beans-dsl')`, so the DSL arrives on this module's compile classpath already. See my note on `grails-core/build.gradle:54`.
##########
grails-beans-dsl/build.gradle:
##########
@@ -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.
+ */
+
+plugins {
+ id 'groovy'
+ id 'java-library'
+ id 'org.apache.grails.buildsrc.properties'
+ id 'org.apache.grails.buildsrc.dependency-validator'
+ id 'org.apache.grails.buildsrc.compile'
+ id 'org.apache.grails.buildsrc.publish'
+ id 'org.apache.grails.buildsrc.sbom'
+ id 'org.apache.grails.buildsrc.vulnerability-scan'
+ id 'org.apache.grails.gradle.grails-code-style'
+ id 'org.apache.grails.gradle.grails-jacoco'
+}
+
+version = projectVersion
+group = 'org.apache.grails'
Review Comment:
This should be a nested group — `org.apache.grails.beandsl` rather than flat `org.apache.grails`.
The repo already partitions published coordinates this way, including for single-module projects, so there is direct precedent:
| group | example |
| --- | --- |
| `org.apache.grails.data` | `grails-datastore-core`, `grails-data-simple`, … |
| `org.apache.grails.web` | `grails-web-core`, `grails-web-mvc`, `grails-encoder`, … |
| `org.apache.grails.testing` | `grails-testing-support-core`, `grails-test-suite-*`, … |
| `org.apache.grails.events` / `.async` / `.forge` / `.gradle` | multi-module |
| `org.apache.grails.i18n` / `.databinding` / `.codecs` / `.common` / `.bootstrap` | **single-module** |
Since the DSL is intended to be on every project's classpath by default (via `grails-core`'s `api`), giving it its own namespace makes that status legible in the coordinates rather than burying it in the flat group.
Worth checking the knock-on: `gradle/publish-root-config.gradle` gates on project *name*, so that list is unaffected, but any BOM constraint or documentation that spells out the coordinates needs to follow the new group.
##########
settings.gradle:
##########
@@ -107,6 +107,9 @@ def skipMicronautProjects = explicitlySkipMicronaut || (!buildJdkSupportsMicrona
include(
'grails-bootstrap',
+ 'grails-beans-dsl',
+ 'grails-beans-dsl-example',
Review Comment:
These two should not be root projects — they belong under `grails-test-examples/` and should follow those conventions.
The move is more than a `git mv`; two of the steps are load-bearing:
1. **The rename is mandatory, not cosmetic.** Root `build.gradle:51-67` populates `testProjects` by matching the project *name* prefix `grails-test-examples`, not the directory. If the directories move but the names don't, the module lands outside `testProjects` while applying `functional-test-config.gradle`, whose `evaluationDependsOn` fan-out (`gradle/functional-test-config.gradle:20-22`) filters on exactly that set — a project that evaluation-depends on itself.
2. **`gradle/test-config.gradle` → `gradle/functional-test-config.gradle`.** All 111 existing modules under `grails-test-examples/` use the latter; none use the former. Note it does *not* contribute `org.junit.platform:junit-platform-launcher`, which `test-config.gradle` does — so both modules need it declared explicitly, the same way `grails-test-examples/hibernate7/standalone-hibernate/build.gradle:44-46` does, or the Spock specs won't launch.
Suggested shape, following the flat-bucket pattern (`grails-test-examples/<dir>` → `:grails-test-examples-<dir>`, as used by `app1`, `cache`, `gsp-layout`, `config-report`):
| now | proposed directory | proposed project |
| --- | --- | --- |
| `grails-beans-dsl-example/` | `grails-test-examples/beans-dsl/` | `:grails-test-examples-beans-dsl` |
| `grails-beans-dsl-plugin-example/` | `grails-test-examples/beans-dsl-plugin/` | `:grails-test-examples-beans-dsl-plugin` |
The `-example` suffix should go — no module under `grails-test-examples/` carries it, the directory already says it.
That means removing lines 111-112 here, then adding both names to the flat `include(...)` block further down this file and a matching `projectDir` line to the block after it — the flat bucket is not auto-scanned, unlike the `hibernate5`/`hibernate7` `listFiles` loops.
One consequence worth being deliberate about: these two modules are the only consumers of the new `autoconfiguration-imports` convention plugin, and `FarewellGrailsPluginAutoDiscoverySpec` is the only test anywhere asserting the generated sibling's FQCN. Once they sit under `grails-test-examples/`, that coverage stops running in core-only CI (`-PonlyCoreTests`). Applying the convention plugin to at least one real converted module — which I suggested separately on `AutoConfigurationImportsPlugin` — would cover that gap properly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5161829897
## ✅ All tests passed ✅
🏷️ Commit: ccee98a603ab5a986d0d6cac5db671cf88811813
▶️ Tests: 67221 executed
⚪️ Checks: 62/62 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "matrei (via GitHub)" <gi...@apache.org>.
matrei commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3702093276
##########
grails-doc/src/en/guide/conf/applicationClass/applicationLifeCycle.adoc:
##########
@@ -34,3 +34,5 @@ class Application extends GrailsAutoConfiguration {
...
}
----
+
+The `Application` class can also define its beans at compile time instead, by annotating it with `@GrailsBeans` — see link:spring.html#springdslAdditional[Configuring Additional Beans].
Review Comment:
Is the `@GrailsBeans` annotation necessary on the `Application` class?
##########
grails-domain-class/src/main/groovy/org/grails/plugins/domain/DomainClassGrailsPlugin.groovy:
##########
@@ -45,15 +55,26 @@ class DomainClassGrailsPlugin extends Plugin {
def dependsOn = [i18n: version]
def loadAfter = ['controllers', 'dataSource']
- @Override
- BeanRegistrar beanRegistrar() {
- return { BeanRegistry registry, Environment environment ->
- // Set default for auto-timestamp annotation caching based on environment if not explicitly configured
- Config config = grailsApplication.config
- if (!config.containsProperty(DatastoreSettings.SETTING_AUTO_TIMESTAMP_CACHE_ANNOTATIONS)) {
- // Not configured - disable caching in development mode to support class reloading
- config.put(DatastoreSettings.SETTING_AUTO_TIMESTAMP_CACHE_ANNOTATIONS,
- !grails.util.Environment.isDevelopmentMode())
+ // The deleted class held grailsApplication and messageSources as fields populated by an
+ // @Autowired constructor. The generated sibling always has a no-arg constructor, so both are
+ // taken as bean method parameters instead - resolved identically by Spring, and only when the
+ // bean that needs them is created rather than when the configuration class is instantiated.
Review Comment:
This comment is redundant.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on code in PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#discussion_r3679575509
##########
grails-mail/build.gradle:
##########
@@ -76,10 +76,14 @@ dependencies {
compileOnly 'org.springframework.boot:spring-boot-autoconfigure' // @AutoConfiguration, @ConditionalOnProperty, @ConfigurationProperties
compileOnly 'org.apache.groovy:groovy' // Provided as this is a Grails plugin
compileOnly 'org.slf4j:slf4j-api' // @Slf4j
+ compileOnly project(':grails-beans-dsl') // comp: @GrailsBeans
Review Comment:
Dropped in `138d014236`, along with the other six — agreed that `compileOnly` was closest to correct but still unnecessary.
See my reply on `grails-cache/build.gradle` for how each removal was verified: compiling is not sufficient evidence, since `compileBeansDsl` fails silently, so `grails-mail`'s generated `MailAutoConfiguration` was checked instead.
##########
grails-beans-dsl/build.gradle:
##########
@@ -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.
+ */
+
+plugins {
+ id 'groovy'
+ id 'java-library'
+ id 'org.apache.grails.buildsrc.properties'
+ id 'org.apache.grails.buildsrc.dependency-validator'
+ id 'org.apache.grails.buildsrc.compile'
+ id 'org.apache.grails.buildsrc.publish'
+ id 'org.apache.grails.buildsrc.sbom'
+ id 'org.apache.grails.buildsrc.vulnerability-scan'
+ id 'org.apache.grails.gradle.grails-code-style'
+ id 'org.apache.grails.gradle.grails-jacoco'
+}
+
+version = projectVersion
+group = 'org.apache.grails'
Review Comment:
Done in `138d014236` — `org.apache.grails.beandsl`.
Checked the knock-on you flagged: `publish-root-config.gradle` gates on project name so it is unaffected, and no BOM constraint or document spells the coordinate out.
##########
settings.gradle:
##########
@@ -107,6 +107,9 @@ def skipMicronautProjects = explicitlySkipMicronaut || (!buildJdkSupportsMicrona
include(
'grails-bootstrap',
+ 'grails-beans-dsl',
+ 'grails-beans-dsl-example',
Review Comment:
Done in `0224df0ecd`, following your table exactly:
| now | project |
| --- | --- |
| `grails-test-examples/beans-dsl/` | `:grails-test-examples-beans-dsl` |
| `grails-test-examples/beans-dsl-plugin/` | `:grails-test-examples-beans-dsl-plugin` |
Both load-bearing steps done as described: the rename, so the name-prefix match puts them in `testProjects` and `functional-test-config.gradle`'s `evaluationDependsOn` fan-out does not have a project depending on itself; and the swap to `functional-test-config.gradle` with `junit-platform-launcher` declared explicitly, since that file does not supply it. Both names are listed in the flat `include(...)` block with their own `projectDir`, since that bucket is not auto-scanned.
All 7 specs run and pass at the new locations. On the CI-coverage consequence you raised: `grails-databinding` now applies the `autoconfiguration-imports` plugin, so it has a consumer inside core-only CI.
##########
grails-beans-dsl-example/build.gradle:
##########
@@ -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.
+ */
+
+plugins {
+ id 'groovy'
+ id 'java-library'
+ 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.buildsrc.autoconfiguration-imports'
+ id 'org.apache.grails.gradle.grails-code-style'
+ id 'org.apache.grails.gradle.grails-jacoco'
+}
+
+version = projectVersion
+group = 'org.apache.grails'
Review Comment:
Done in `0224df0ecd`: `group = 'examples'`, `functional-test-config.gradle` plus an explicit `junit-platform-launcher`, and `grails-code-style`/`grails-jacoco` dropped. Agreed on the last — no other module there applies either, and example code does not belong in the violation and coverage reports. `autoconfiguration-imports` kept.
One departure: this module **keeps** `implementation project(':grails-beans-dsl')`. It deliberately has no `grails-core` on its classpath — that is the whole point of the split documented in the sibling module — so the `api` that carries the DSL everywhere else does not reach it. The line now records that. The plugin example does have `grails-core` and dropped its declaration.
##########
grails-beans-dsl-plugin-example/build.gradle:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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 'groovy'
+ id 'java-library'
+ 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.buildsrc.autoconfiguration-imports'
+ id 'org.apache.grails.gradle.grails-code-style'
+ id 'org.apache.grails.gradle.grails-jacoco'
+}
+
+version = projectVersion
+group = 'org.apache.grails'
Review Comment:
Done in `0224df0ecd`, same set as the sibling module: `group = 'examples'`, `functional-test-config.gradle` plus an explicit `junit-platform-launcher`, `grails-code-style`/`grails-jacoco` dropped, `autoconfiguration-imports` kept.
Here the `grails-beans-dsl` declaration *is* dropped, since `grails-core` carries it — unlike `grails-test-examples/beans-dsl`, which deliberately has no `grails-core`.
The comment that referred to the sibling by its old name now points at `grails-test-examples/beans-dsl`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5135135853
## ✅ All tests passed ✅
🏷️ Commit: 297767a923f713e626f3ea4db686fa91b60d5aa1
▶️ Tests: 67400 executed
⚪️ Checks: 62/62 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5141074238
## ✅ All tests passed ✅
🏷️ Commit: 9f18a77067b2c27ec7792362dc09032000666dd0
▶️ Tests: 66861 executed
⚪️ Checks: 62/62 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5026067278
## ✅ All tests passed ✅
🏷️ Commit: ff2241926c76517a9189be7d0415d3db222fa6e3
▶️ Tests: 38502 executed
⚪️ Checks: 59/59 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5065883167
The `UrlMappingsAutoConfiguration` conversion attempted in the review above is now in the branch (5e9e162e99), in the same shape as the `grails-i18n` one. Imports and comments are trimmed here for brevity; each block's linked filename is the verbatim, commit-pinned source.
Before, [`UrlMappingsAutoConfiguration.java`](https://github.com/codeconsole/grails-core/blob/32ead2bbc405c7b2d6fec097e05e0a04a375e374/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsAutoConfiguration.java#L20-L102) (since deleted):
```java
@AutoConfiguration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@EnableConfigurationProperties({ GrailsCorsConfiguration.class })
public class UrlMappingsAutoConfiguration {
@Value("${" + Settings.WEB_LINK_GENERATOR_USE_CACHE + ":#{null}}")
private Boolean cacheUrls;
@Value("${" + Settings.SERVER_URL + ":#{null}}")
private String serverURL;
@Bean(UrlConverter.BEAN_NAME)
@ConditionalOnMissingBean(name = UrlConverter.BEAN_NAME)
@ConditionalOnProperty(name = Settings.WEB_URL_CONVERTER, havingValue = "camelCase", matchIfMissing = true)
public UrlConverter camelCaseUrlConverter() {
return new CamelCaseUrlConverter();
}
@Bean(UrlConverter.BEAN_NAME)
@ConditionalOnMissingBean(name = UrlConverter.BEAN_NAME)
@ConditionalOnProperty(name = Settings.WEB_URL_CONVERTER, havingValue = "hyphenated")
public UrlConverter hyphenatedUrlConverter() {
return new HyphenatedUrlConverter();
}
@Bean
@ConditionalOnMissingBean(name = LinkGenerator.BEAN_NAME)
public LinkGenerator grailsLinkGenerator() {
if (cacheUrls == null) {
cacheUrls = !Environment.isDevelopmentMode() && !Environment.getCurrent().isReloadEnabled();
}
return cacheUrls ? new CachingLinkGenerator(serverURL) : new DefaultLinkGenerator(serverURL);
}
@Bean
@ConditionalOnMissingBean(CorsFilter.class)
@ConditionalOnProperty(name = Settings.SETTING_CORS_FILTER, havingValue = "true", matchIfMissing = true)
public GrailsCorsFilter grailsCorsFilter(GrailsCorsConfiguration grailsCorsConfiguration) {
return new GrailsCorsFilter(grailsCorsConfiguration);
}
@Bean
@ConditionalOnMissingBean(UrlMappingsErrorPageCustomizer.class)
public UrlMappingsErrorPageCustomizer urlMappingsErrorPageCustomizer(ObjectProvider<UrlMappings> urlMappingsProvider) {
UrlMappingsErrorPageCustomizer errorPageCustomizer = new UrlMappingsErrorPageCustomizer();
errorPageCustomizer.setUrlMappings(urlMappingsProvider.getIfAvailable());
return errorPageCustomizer;
}
@Bean
@ConditionalOnMissingBean(UrlMappingsInfoHandlerAdapter.class)
public UrlMappingsInfoHandlerAdapter urlMappingsInfoHandlerAdapter() {
return new UrlMappingsInfoHandlerAdapter();
}
}
```
After — [`UrlMappingsGrailsPlugin.groovy`](https://github.com/codeconsole/grails-core/blob/5e9e162e998da4ae9acaf04bb85fc6445c84c755/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPlugin.groovy#L19-L114)'s class declaration and `beans` block (the rest of the file — `beanRegistrar()`, `onChange()`, `DefaultUrlMappings` — is pre-existing plugin logic, untouched by the conversion):
```groovy
@CompileStatic
@GrailsBeans
@AutoConfiguration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@EnableConfigurationProperties([GrailsCorsConfiguration])
class UrlMappingsGrailsPlugin extends Plugin {
def watchedResources = ['file:./grails-app/controllers/*UrlMappings.groovy']
def version = GrailsUtil.getGrailsVersion()
def dependsOn = [core: version]
def loadAfter = ['controllers']
def beans = {
field('cacheUrls', Boolean).value(Settings.WEB_LINK_GENERATOR_USE_CACHE, '#{null}')
field('serverURL', String).value(Settings.SERVER_URL, '#{null}')
bean('grailsUrlConverter', UrlConverter).conditionalOnMissingBeanName().annotate(ConditionalOnProperty, name: 'grails.web.url.converter', havingValue: 'camelCase', matchIfMissing: true) {
new CamelCaseUrlConverter()
}
bean('grailsUrlConverter', UrlConverter).conditionalOnMissingBeanName().annotate(ConditionalOnProperty, name: 'grails.web.url.converter', havingValue: 'hyphenated') {
new HyphenatedUrlConverter()
}
bean('grailsLinkGenerator', LinkGenerator).conditionalOnMissingBeanName() {
if (cacheUrls == null) {
cacheUrls = !grails.util.Environment.isDevelopmentMode() &&
!grails.util.Environment.getCurrent().isReloadEnabled()
}
cacheUrls ? new CachingLinkGenerator(serverURL) : new DefaultLinkGenerator(serverURL)
}
bean(GrailsCorsFilter).conditionalOnMissingBean(CorsFilter).annotate(ConditionalOnProperty, name: 'grails.cors.filter', havingValue: 'true', matchIfMissing: true) { GrailsCorsConfiguration grailsCorsConfiguration ->
new GrailsCorsFilter(grailsCorsConfiguration)
}
bean(UrlMappingsErrorPageCustomizer).conditionalOnMissingBean() { ObjectProvider<UrlMappings> urlMappingsProvider ->
def errorPageCustomizer = new UrlMappingsErrorPageCustomizer()
errorPageCustomizer.setUrlMappings(urlMappingsProvider.getIfAvailable())
errorPageCustomizer
}
bean(UrlMappingsInfoHandlerAdapter).conditionalOnMissingBean() {
new UrlMappingsInfoHandlerAdapter()
}
}
```
The two mutually exclusive `grailsUrlConverter` variants share one Spring bean name, selected by `@ConditionalOnProperty` — the pattern the compile error used to reject. The generated sibling regains the exact `UrlMappingsAutoConfiguration` class identity via the `*GrailsPlugin` naming convention, so the module's hand-maintained `AutoConfiguration.imports` entry is untouched, and the `ObjectProvider<UrlMappings>` parameter's generic signature survives into the bytecode (javap-verified). One fidelity note: the `@ConditionalOnProperty` `name:` attributes are literals mirroring `Settings.WEB_URL_CONVERTER`/`Settings.SETTING_CORS_FILTER` — an annotation attribute value must be an inline constant — while the two `field(...).value(...)` injections keep their bare `Settings` constant keys, which the DSL folds at transform time. The url-converter selection and link-generator configuration, previously untested, now have spec coverage (03209d1209).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "codeconsole (via GitHub)" <gi...@apache.org>.
codeconsole commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5066133755
The `grails-mail` conversion (6e4a52013d), same pattern. This one exercises parameter-level annotations carrying through closure parameters — `mailSender`'s optional session is declared `@Autowired(required = false) @Qualifier('mailSession')` on the closure parameter, exactly as it was on the original method — and wires `grails-beans-dsl` as `compileOnly`, matching this module's provided-scope pattern for its Spring dependencies (the transform is compile-time only; the retained `@GrailsBeans` annotation is inert when the jar is absent). Imports and comments are trimmed here; each linked filename is the verbatim, commit-pinned source.
Before, [`MailAutoConfiguration.groovy`](https://github.com/codeconsole/grails-core/blob/53dcb874db7621286d37471412cab288990c9eef/grails-mail/src/main/groovy/grails/plugins/mail/MailAutoConfiguration.groovy#L36-L118) (since deleted):
```groovy
@CompileStatic
@AutoConfiguration
@EnableConfigurationProperties(MailConfigurationProperties)
class MailAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = 'grails.mail', name = 'jndiName')
JndiObjectFactoryBean mailSession(MailConfigurationProperties mailProperties) {
def factory = new JndiObjectFactoryBean()
factory.jndiName = mailProperties.jndiName
return factory
}
@Bean
@ConditionalOnMissingBean
JavaMailSender mailSender(
@Autowired(required = false)
@Qualifier('mailSession') Session mailSession,
MailConfigurationProperties mailProperties) {
def mailSender = new JavaMailSenderImpl()
if (mailProperties.host) {
mailSender.host = mailProperties.host
} else if (!mailProperties.jndiName) {
def envHost = System.getenv()['SMTP_HOST']
if (envHost) {
mailSender.host = envHost
} else {
mailSender.host = 'localhost'
}
}
if (mailProperties.encoding) {
mailSender.defaultEncoding = mailProperties.encoding
} else if (!mailProperties.jndiName) {
mailSender.defaultEncoding = 'utf-8'
}
if (mailSession != null) {
mailSender.session = mailSession
}
if (mailProperties.port) {
mailSender.port = mailProperties.port
}
if (mailProperties.username) {
mailSender.username = mailProperties.username
}
if (mailProperties.password) {
mailSender.password = mailProperties.password
}
if (mailProperties.protocol) {
mailSender.protocol = mailProperties.protocol
}
if (mailProperties.props) {
mailSender.javaMailProperties = mailProperties.props
}
return mailSender
}
@Bean
@ConditionalOnMissingBean
MailMessageBuilderFactory mailMessageBuilderFactory(
MailSender mailSender,
MailMessageContentRenderer mailMessageContentRenderer) {
new MailMessageBuilderFactory(mailSender, mailMessageContentRenderer)
}
@Bean
@ConditionalOnMissingBean
MailMessageContentRenderer mailMessageContentRenderer(
GroovyPagesTemplateEngine groovyPagesTemplateEngine,
GroovyPagesUriService groovyPagesUriService,
GrailsApplication grailsApplication,
GrailsPluginManager pluginManager) {
new MailMessageContentRenderer(groovyPagesTemplateEngine, groovyPagesUriService, grailsApplication, pluginManager)
}
@Bean
@ConditionalOnMissingBean
MailService mailService(MailConfigurationProperties mailConfigurationProperties,
MailMessageBuilderFactory mailMessageBuilderFactory) {
new MailService(mailConfigurationProperties, mailMessageBuilderFactory)
}
}
```
After — [`MailGrailsPlugin.groovy`](https://github.com/codeconsole/grails-core/blob/6e4a52013d3103e1f8ccaffb363008da2cc26ec6/grails-mail/src/main/groovy/grails/plugins/mail/MailGrailsPlugin.groovy#L36-L139)'s class declaration and `beans` block (the plugin's metadata properties between them are elided below, unchanged by the conversion):
```groovy
@CompileStatic
@GrailsBeans
@AutoConfiguration
@EnableConfigurationProperties(MailConfigurationProperties)
class MailGrailsPlugin extends Plugin {
// ... pre-existing plugin metadata properties, unchanged ...
def beans = {
bean('mailSession', JndiObjectFactoryBean).conditionalOnMissingBean().annotate(ConditionalOnProperty, prefix: 'grails.mail', name: 'jndiName') { MailConfigurationProperties mailProperties ->
def factory = new JndiObjectFactoryBean()
factory.jndiName = mailProperties.jndiName
return factory
}
bean('mailSender', JavaMailSender).conditionalOnMissingBean() { @Autowired(required = false) @Qualifier('mailSession') Session mailSession, MailConfigurationProperties mailProperties ->
def mailSender = new JavaMailSenderImpl()
if (mailProperties.host) {
mailSender.host = mailProperties.host
} else if (!mailProperties.jndiName) {
def envHost = System.getenv()['SMTP_HOST']
if (envHost) {
mailSender.host = envHost
} else {
mailSender.host = 'localhost'
}
}
if (mailProperties.encoding) {
mailSender.defaultEncoding = mailProperties.encoding
} else if (!mailProperties.jndiName) {
mailSender.defaultEncoding = 'utf-8'
}
if (mailSession != null) {
mailSender.session = mailSession
}
if (mailProperties.port) {
mailSender.port = mailProperties.port
}
if (mailProperties.username) {
mailSender.username = mailProperties.username
}
if (mailProperties.password) {
mailSender.password = mailProperties.password
}
if (mailProperties.protocol) {
mailSender.protocol = mailProperties.protocol
}
if (mailProperties.props) {
mailSender.javaMailProperties = mailProperties.props
}
return mailSender
}
bean(MailMessageBuilderFactory).conditionalOnMissingBean() { MailSender mailSender, MailMessageContentRenderer mailMessageContentRenderer ->
new MailMessageBuilderFactory(mailSender, mailMessageContentRenderer)
}
bean(MailMessageContentRenderer).conditionalOnMissingBean() { GroovyPagesTemplateEngine groovyPagesTemplateEngine, GroovyPagesUriService groovyPagesUriService, GrailsApplication grailsApplication, GrailsPluginManager pluginManager ->
new MailMessageContentRenderer(groovyPagesTemplateEngine, groovyPagesUriService, grailsApplication, pluginManager)
}
bean(MailService).conditionalOnMissingBean() { MailConfigurationProperties mailConfigurationProperties, MailMessageBuilderFactory mailMessageBuilderFactory ->
new MailService(mailConfigurationProperties, mailMessageBuilderFactory)
}
}
```
The generated sibling regains the exact `MailAutoConfiguration` class identity, so the `AutoConfiguration.imports` entry is untouched, and `@EnableConfigurationProperties(MailConfigurationProperties)` moves onto it at compile time. The plugin class is now `@CompileStatic`, preserving the deleted class's static compilation — javap shows no `invokedynamic` call sites, and `RuntimeVisibleParameterAnnotations` on the generated `mailSender` method's `Session` parameter. The auto-configuration previously had no test coverage at all; the new `MailAutoConfigurationSpec` asserts the defaulted and property-driven mail sender configuration (the context starts with no `mailSession` bean, proving the optional parameter), the `jndiName`-gated JNDI session bean, user back-off, and the full mail service chain.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add @GrailsBeans: compile bean-wiring DSL into real @AutoConfiguration classes [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16019:
URL: https://github.com/apache/grails-core/pull/16019#issuecomment-5067073093
## ✅ All tests passed ✅
🏷️ Commit: 7d17c3ac4eb8a059a99d70ca9ae9fac46474a744
▶️ Tests: 65838 executed
⚪️ Checks: 61/61 completed
---
_Learn more about TestLens at [testlens.app](https://testlens.app)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org