使用Kotlin的Spring Boot-@Value注释无法按预期工作

Adr*_*aro 6 spring properties kotlin spring-boot

我正在使用Kotlin开发Spring Boot应用程序。由于需要连接到外部API(多云),因此我决定向我的应用程序添加一个配置类,以存储(并从VCS中隐藏)我的敏感数据,例如用户名,密码或API密钥。

所以这就是我所做的:

我创建了一个Config类:

package demons

import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.PropertySource

@Configuration
@PropertySource("classpath:application.properties")
class AppConfig {
    @Value("\${test.prop}")
    val testProperty: String? = null
}
Run Code Online (Sandbox Code Playgroud)

然后我在我的application.properties文件中添加了一个test.prop条目

test.prop=TEST
Run Code Online (Sandbox Code Playgroud)

但是,在我运行的每个测试中,创建AppConfig的实例后,他的testProperty属性null不是string TEST

例如,此代码段:

val config = AppConfig()
System.out.println(config.testProperty)
Run Code Online (Sandbox Code Playgroud)

将打印出:

null
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用单独的.properties文件代替默认的.properties文件,myproperties.properties并将变量声明为lateinit var。在这最后一种情况下,变量似乎永远不会初始化:

kotlin.UninitializedPropertyAccessException: lateinit property testProperty has not been initialized
Run Code Online (Sandbox Code Playgroud)

我想念什么?

nic*_*ild 6

问题是您正在AppConfig通过构造函数创建自己的实例:

val config = AppConfig()

尽管此类可能具有Spring批注,但是如果您自己创建实例,则不是Spring管理的。

我建议您从其他答案中提到链接中借用。有使用SpringBoot为您创建Spring应用程序的好例子。在下面,我创建了测试的“合并”示例以及链接中的示例。无需指定属性文件,因为application.properties默认情况下用作属性源。

@SpringBootApplication
class AppConfig {
    @Value("\${test.prop}")
    val testProperty: String? = null
}

fun main(args: Array<String>) {
    val appContext = SpringApplication.run(AppConfig::class.java, *args)
    val config = appContext.getBean(AppConfig::class.java)
    System.out.println(config.testProperty)
}
Run Code Online (Sandbox Code Playgroud)