Skip to content

Commit 01b2856

Browse files
committed
Document Kotlin internal modifier impact on @Bean
Closes gh-31985
1 parent 6dca7b2 commit 01b2856

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: framework-docs/modules/ROOT/pages/languages/kotlin/spring-projects-in.adoc

+37
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,9 @@ does not require the `kotlin-noarg` plugin if the module uses Spring Data object
9797
[[injecting-dependencies]]
9898
== Injecting Dependencies
9999

100+
[[favor-constructor-injection]]
101+
=== Favor constructor injection
102+
100103
Our recommendation is to try to favor constructor injection with `val` read-only (and
101104
non-nullable when possible) {kotlin-docs}/properties.html[properties],
102105
as the following example shows:
@@ -130,7 +133,41 @@ as the following example shows:
130133
}
131134
----
132135

136+
[[internal-functions-name-mangling]]
137+
=== Internal functions name mangling
138+
139+
Kotlin functions with the `internal` {kotlin-docs}/visibility-modifiers.html#class-members[visibility modifier] have
140+
their names mangled when compiled to JVM bytecode, which has a side effect when injecting dependencies by name.
141+
142+
For example, this Kotlin class:
143+
[source,kotlin,indent=0]
144+
----
145+
@Configuration
146+
class SampleConfiguration {
147+
148+
@Bean
149+
internal fun sampleBean() = SampleBean()
150+
}
151+
----
152+
153+
Translates to this Java representation of the compiled JVM bytecode:
154+
[source,java,indent=0]
155+
----
156+
@Configuration
157+
@Metadata(/* ... */)
158+
public class SampleConfiguration {
159+
160+
@Bean
161+
@NotNull
162+
public SampleBean sampleBean$demo_kotlin_internal_test() {
163+
return new SampleBean();
164+
}
165+
}
166+
----
133167

168+
As a consequence, the related bean name represented as a Kotlin string is `"sampleBean\$demo_kotlin_internal_test"`,
169+
instead of `"sampleBean"` for the regular `public` function use-case. Make sure to use the mangled name when injecting
170+
such bean by name.
134171

135172
[[injecting-configuration-properties]]
136173
== Injecting Configuration Properties

0 commit comments

Comments
 (0)