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.

推荐答案

通过在配置中声明以下bean,可以自定义使用的前缀:

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

如果您有任何使用${...}语法的现有代码(如Spring Boot actuators或@LocalServerPort),您应该声明:

@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.

对于配置为@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)的Spring Boot测试,可以使用@LocalServerPort而不是@Value("\${local.server.port}").

@ConfigurationProperties将是一个更好的 Select ,尤其是对于Kotlin数据类,但目前必须使用具有可为null的var属性的Kotlin类,因为只支持getter/setter.你可以投票支持this issue或发表 comments ,以表明你有兴趣在Spring Boot 2中获得支持.十、

Kotlin相关问答推荐

调用即发即忘方法--哪个作用域?

解决Microronaut中多个可能的Bean候选者冲突

Kotlin-stdlib中的模拟扩展函数

新的jOOQ Gradle插件无法正确处理自引用关系

如何在 Kotlin 中将with代码转换为完整代码?

is return inside function definition 也是 kotlin 中的表达式

使用纯 Kotlin 函数作为 Junit5 方法源

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

使用 Kotlin 协程时 Room dao 类出错

为什么 IntelliJ Idea 无法识别我的 Spek 测试?

模拟异常 - 没有找到答案

runOnUiThread 没有调用

有没有办法在数据类构建时转换属性的值?

main函数和常规函数有什么区别?

spring.config.location 在 Spring Boot 2.0.0 M6 上不起作用

不推荐使用仅限生命周期的LifecycleEvent

WebFlux 功能:如何检测空 Flux 并返回 404?

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有

在 Kotlin 中编写一个等于 Int.MIN_VALUE 的十六进制整数文字

RxJava - 每秒发出一个 observable