Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot 如何在SpringBoot kotlin中使用application.yaml中的变量_Spring Boot_Kotlin - Fatal编程技术网

Spring boot 如何在SpringBoot kotlin中使用application.yaml中的变量

Spring boot 如何在SpringBoot kotlin中使用application.yaml中的变量,spring-boot,kotlin,Spring Boot,Kotlin,我需要使用applications.yaml文件中声明的变量,例如: num_error: value: "error" result: 1 我有一个类试着这样称呼它: @ConfigurationProperties(prefix = "num_error") @Component class NumError { companion object { lateinit var value: String lateinit var re

我需要使用applications.yaml文件中声明的变量,例如:

num_error:
    value: "error"
    result: 1
我有一个类试着这样称呼它:

@ConfigurationProperties(prefix = "num_error")
@Component
class NumError {
    companion object {
        lateinit var value: String
        lateinit var result: Number
     }
 }
然而,当我尝试使用
numeror.value
调用这个类时,我得到一个错误

lateinit property value has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property value has not been initialized

我做错了什么,为什么会发生这种错误

您不需要有
伴生对象
,而且自Spring boot 2.2以来,您可以使用构造函数绑定使其工作

@ConstructorBinding
@ConfigurationProperties(prefix = "num_error")
data class NumError(
    val value: String, val result: Number
)
确保包含以下依赖项

dependencies {
  annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
}
编辑

对于较旧的版本,直接在类中定义变量,而不是
伴随对象

@Configuration
@ConfigurationProperties(prefix = "num_error")
class NumError {

  var value: String = "some default value",
  var result: Number? = null
} 

我试过这么做,但有两个错误,“未解析引用:ConstructorBinding”和“Data class必须至少有一个主构造函数参数”spring启动版本是什么?我使用的是2.1.3.RELEASE,但我无法更新它。现在使用的“ConversionErrorProperties()似乎不起作用.value'获取值,但它始终使用与获取结果相同的默认值:(您不应该初始化类,而是自动连接bean
@Autowired ConversionErrorProperties props;