【问题标题】:Spring Boot with Kotlin - @Value annotation not working as expected带有 Kotlin 的 Spring Boot - @Value 注释未按预期工作
【发布时间】:2018-12-18 14:08:16
【问题描述】:

我正在使用 Kotlin 开发一个 Spring Boot 应用程序。由于我需要连接到外部 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

比如这个sn-p:

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

会打印出来:

null

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

kotlin.UninitializedPropertyAccessException: lateinit property testProperty has not been initialized

我错过了什么?

【问题讨论】:

    标签: spring spring-boot properties kotlin


    【解决方案1】:

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

    val config = AppConfig()
    

    虽然此类可能有 Spring 注释,但如果您自己创建实例,则它不是 Spring 管理的。

    我建议您从link you mentioned in my other 答案中借用。有使用 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)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 2015-12-19
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多