What is the easiest way to change the prefix and suffix for the property placeholder in Spring Boot?
The default is @Value("${some.property}")
, however this looks ugly in Kotlin, since it needs to be escaped - ${something} is a language feature in Kotlin for String templates.
It is possible to customize the prefix used by declaring the following beans in your configuration:
@Bean
fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
}
if you have any existing code (like Spring Boot actuators or @LocalServerPort
) that is using the ${...}
syntax, you should declare:
@Bean
fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
setIgnoreUnresolvablePlaceholders(true)
}
@Bean
fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
Escaping the dollar like in @Value("\${some.property}")
is another possible option that require no @Bean
declaration.
For Spring Boot tests configured with @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
you can use @LocalServerPort
instead of @Value("\${local.server.port}")
.
@ConfigurationProperties
would be a better alternative, especially with Kotlin data classes, but currently you have to use Kotlin classes with nullable var
properties since only getter/setter are supported. You can vote for this issue or comment to show your interest in getting that supported in Spring Boot 2.x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With