问题 Kotlin和Spring Boot @ConfigurationProperties


如何正确初始化ConfigurationProperties 春季启动 同 科特林

目前 我喜欢在下面的例子中:

 @ConfigurationProperties("app")
 class Config {
     var foo: String? = null
 }

但它实际上看起来很丑陋 foo 不是一个 var可爱,foo是 不变  val你和 应该在启动期间初始化,并且将来不会改变


5502
2017-08-30 06:09


起源

这很好。 Spring使用JavaBean绑定,因此您需要getter / setter。 ConfigurationProperties 是用于类型安全配置,它不是 data 类。 - Abhijit Sarkar
看到 github.com/spring-projects/spring-boot/issues/8762 这是关于支持正确的不可变数据类的决定 @ConfigurationProperties。 - Sébastien Deleuze


答案:


如中所述 文档: 一个 ”Java Bean“必须提供才能使用 ConfigurationProperties。这意味着您的属性需要具有getter和setter val 目前是不可能的。

getter和setter通常是必需的,因为绑定是通过标准的Java Beans属性描述符,就像在Spring MVC中一样。有些情况下可能会省略定位器[...]

有一个 公开问题 与您的用例相关的Kotlin: https://github.com/spring-projects/spring-boot/issues/8762


10
2017-08-30 07:29





@Value("\${some.property.key:}")
lateinit var foo:String

可以这样使用


0
2017-08-30 06:24



谢谢,你评论。我知道 @Value 注释,但我不这么认为,因为它产生了很多样板代码, @ConfigurationProperties 绝对更好。 - Sonique


这就是我做的方式:

application.properties

my.prefix.myValue=1

MyProperties.kt

import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component

@Component
@ConfigurationProperties(prefix = "my.prefix")
class MyProperties
{
    private var myValue = 0
    fun getMyValue(): Int {
        return myValue;
    }

    fun setMyValue(value: Int){
        myValue = value
    }
}

MyService.kt

@Component
class MyService(val myProperties: MyProperties) {
    fun doIt() {
        System.console().printf(myProperties.getMyValue().toString())
    }
}

0
2018-05-16 18:05



这对我不起作用。我还添加了注释 @EnableConfigurationProperties,但仍然没有成功。 - Ray Hunter


以下是我使用application.yml文件的方法。

myconfig:
  my-host: ssl://example.com
  my-port: 23894
  my-user: user
  my-pass: pass

这是kotlin文件:

@Configuration
@ConfigurationProperties(prefix = "myconfig")
class MqttProperties {
    lateinit var myHost: String
    lateinit var myPort: String
    lateinit var myUser: String
    lateinit var myPass: String    
}

这对我很有用。


0
2018-06-13 02:55