Skip to content

Commit 884fc40

Browse files
committed
Add "Injecting configuration properties" to Kotlin ref doc
Issue: SPR-15659
1 parent 75114bd commit 884fc40

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/docs/asciidoc/kotlin.adoc

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,48 @@ class YourBean {
394394
}
395395
----
396396

397+
=== Injecting configuration properties
398+
399+
In Java, you can inject configuration properties using annotations like `@Value("${property}")`,
400+
however in Kotlin `$` is a reserved character that is used for https://kotlinlang.org/docs/reference/idioms.html#string-interpolation[string interpolation].
401+
402+
In order to use `@Value` in Kotlin, you have to escape the `$` character by writing `@Value("\${property}")`.
403+
404+
As an alternative, you can also customize the properties placeholder prefix by declaring
405+
the following beans in your configuration:
406+
407+
[source,kotlin]
408+
----
409+
@Bean
410+
fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
411+
setPlaceholderPrefix("%{")
412+
}
413+
----
414+
415+
If you have any existing code (like Spring Boot actuators or `@LocalServerPort`) that is
416+
using the `${...}` syntax, you should declare the following beans in your configuration:
417+
418+
[source,kotlin]
419+
----
420+
@Bean
421+
fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
422+
setPlaceholderPrefix("%{")
423+
setIgnoreUnresolvablePlaceholders(true)
424+
}
425+
426+
@Bean
427+
fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
428+
----
429+
430+
[NOTE]
431+
====
432+
If you are using Spring Boot, you would probably be interested in using
433+
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties[`@ConfigurationProperties`]
434+
instead of `@Value`, but currently you have to use it with nullable `var` (which is far from ideal)
435+
properties since immutable classes initialized by constructor are not support yet.
436+
See https://github.com/spring-projects/spring-boot/issues/8762[this issue] for more details.
437+
====
438+
397439
=== Easy testing Kotlin and JUnit 5
398440

399441
Kotlin allows to specify meaningful test function names betweeen backticks,

0 commit comments

Comments
 (0)