簡體   English   中英

帶有 Kotlin 的 Spring Boot - @Value 注釋未按預期工作

[英]Spring Boot with Kotlin - @Value annotation not working as expected

我正在使用 Kotlin 開發 Spring 啟動應用程序。 由於我需要連接到外部 API(cloudinary),我決定向我的應用程序添加一個配置類,以便存儲(並向 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
}

然后我在 application.properties 文件中添加了一個 test.prop 條目

test.prop=TEST

但是,在我運行的每個測試中,在創建 AppConfig 實例后,他的 testProperty 屬性為null而不是字符串TEST

例如這個片段:

val config = AppConfig()
System.out.println(config.testProperty)

會打印出來:

null

我還嘗試使用單獨的 .properties 文件而不是像myproperties.properties這樣的默認文件,並將變量聲明為lateinit var 在最后一種情況下,變量似乎從未被初始化:

kotlin.UninitializedPropertyAccessException: lateinit property testProperty has not been initialized

我錯過了什么?

問題是您正在通過構造函數自己創建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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM