繁体   English   中英

如何在 kotlin 中为原始类型使用 @Autowired 或 @Value 之类的 spring 注释?

[英]how to use spring annotations like @Autowired or @Value in kotlin for primitive types?

使用 spring 注释自动装配非原始类型,例如

@Autowired
lateinit var metaDataService: MetaDataService

作品。

但这不起作用:

@Value("\${cacheTimeSeconds}")
lateinit var cacheTimeSeconds: Int

有错误:

原始类型不允许使用 lateinit 修饰符。

如何将原始属性自动装配到 kotlin 类中?

您还可以在构造函数中使用 @Value 注释:

class Test(
    @Value("\${my.value}")
    private val myValue: Long
) {
        //...
  }

这样做的好处是您的变量是 final 且不可为空的。 我也更喜欢构造函数注入。 它可以使测试更容易。

@Value("\\${cacheTimeSeconds}") lateinit var cacheTimeSeconds: Int

应该

@Value("\${cacheTimeSeconds}")
val cacheTimeSeconds: Int? = null

我只是像这样使用Number而不是Int ......

    @Value("\${cacheTimeSeconds}")
    lateinit var cacheTimeSeconds: Number

其他选择是做其他人之前提到的......

    @Value("\${cacheTimeSeconds}")
    var cacheTimeSeconds: Int? = null

或者您可以简单地提供一个默认值,例如...

    @Value("\${cacheTimeSeconds}")
    var cacheTimeSeconds: Int = 1

在我的例子中,我必须得到一个Boolean类型的属性,它在 Kotlin 中是原始类型,所以我的代码看起来像这样......

    @Value("\${myBoolProperty}")
    var myBoolProperty: Boolean = false

尝试设置默认值

    @Value("\${a}")
    val a: Int = 0

在 application.properties 中

a=1

在代码中

package com.example.demo

import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.stereotype.Component

@SpringBootApplication
class DemoApplication

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}

@Component
class Main : CommandLineRunner {

    @Value("\${a}")
    val a: Int = 0

    override fun run(vararg args: String) {
        println(a)
    }
}

它将打印1

或使用构造函数注入

@Component
class Main(@Value("\${a}") val a: Int) : CommandLineRunner {

    override fun run(vararg args: String) {
        println(a)
    }
}

问题不在于注解,而是primitive 和lateinit的混合,根据这个问题,Kotlin 不允许lateinit原语。

解决方法是更改​​为可空类型Int? ,或者不使用lateinit

这个TryItOnline显示了这个问题。

Kotlin 在 Java 代码中将 Int 编译为 int。 Spring 需要非原始类型进行注入,所以你应该使用 Int? / 布尔值? / 长? 等。可空类型 kotlin 编译为 Integer / Boolean / 等。

没有默认值和外部构造函数

从:

@Value("\${cacheTimeSeconds}") lateinit var cacheTimeSeconds: Int

到:

@delegate:Value("\${cacheTimeSeconds}")  var cacheTimeSeconds by Delegates.notNull<Int>()

祝你好运

Kotlin 没有原始类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM