Spring Boot:更改属性占位符的能指
在Spring Boot中更改属性占位符的前缀和后缀最简单的方法是什么?
默认值是@Value("${some.property}")
,但是这在Kotlin中看起来很丑,因为它需要被转义 – $ {something}是Kotlin中String模板的语言特性。
可以通过在配置中声明以下bean来自定义前缀:
@Bean fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply { setPlaceholderPrefix("%{") }
如果您有任何使用${...}
语法的现有代码(如Spring Boot执行器或@LocalServerPort
),则应该声明:
@Bean fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply { setPlaceholderPrefix("%{") setIgnoreUnresolvablePlaceholders(true) } @Bean fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
在@Value("\${some.property}")
转义美元是另一个不需要@Bean
声明的可能选项。
对于使用@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
配置的Spring Boot测试,可以使用@LocalServerPort
而不是@Value("\${local.server.port}")
。
@ConfigurationProperties
会是一个更好的选择,特别是对于Kotlin数据类,但是由于只支持getter / setter,所以目前您必须使用具有可为空的var
属性的Kotlin类。 您可以对此问题或评论进行投票,以显示您对获得Spring Boot 2.x支持的兴趣。
使用dox提供的答案的建议,我结束了以下类似的事情:
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 } }
在Spring中, @ConfigurationProperties
对象需要遵循Java Beans模式,因此是可变的。 对我来说,配置好像在整个应用程序的生命周期中应该是静态的,所以不是添加关于状态的推理的复杂性,而是注入不可变的接口。
他们有一个使用@ConfigurationProperties
注解的java类的新特性。 这在Kotlin看起来不错,并且正在重构保存。 你应该试试看: