Spring Download: change placeholder id

What is the easiest way to change the prefix and suffix for a property placeholder in Spring Boot?

By default, @Value("${some.property}") , however it looks ugly in Kotlin since it needs to be escaped - $ {something} is the language function in Kotlin templates for String.

+8
java spring spring-boot kotlin
source share
3 answers

You can customize the prefix used by declaring the following beans in your configuration:

 @Bean fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply { setPlaceholderPrefix("%{") } 

if you have existing code (such as Spring Boot Drives or @LocalServerPort ) that uses the ${...} syntax, you must declare:

 @Bean fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply { setPlaceholderPrefix("%{") setIgnoreUnresolvablePlaceholders(true) } @Bean fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer() 

Exiting the dollar, as in @Value("\${some.property}") , is another possible option that does not require an @Bean .

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 for now you need to use Kotlin classes with a null value of var , since only getter / setter is supported. You can vote for this issue or comment to show your interest in getting support in Spring Boot 2.x.

+20
source share

Using the advice from the answer provided by dox, I ended up with something like:

 public interface TokenAuthenticationConfig { public fun apiKey() : String } @Component @ConfigurationProperties(prefix = "service.api") public open class TokenAuthenticationConfigImpl : TokenAuthenticationConfig { public var apiKey : String constructor() { this.apiKey = "" } override fun apiKey(): String { return this.apiKey } } 

In Spring @ConfigurationProperties objects must follow the Java Beans pattern and therefore be mutable. It seems to me that the configuration is usually static throughout the entire life cycle of the application, and instead of adding the complexity of reasoning about the state, an immutable interface is introduced instead.

+2
source share

They have a new feature using java classes annotated with @ConfigurationProperties . It looks good in Kotlin, and refactoring is preserved. You must try:

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties

+1
source share

All Articles