Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: Change property placeholder signifier

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.

like image 337
Jasper Blues Avatar asked Nov 20 '15 07:11

Jasper Blues


1 Answers

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.

like image 176
Sébastien Deleuze Avatar answered Sep 19 '22 13:09

Sébastien Deleuze