繁体   English   中英

原始类型的属性上不允许使用'lateinit'修饰符-Kotlin

[英]'lateinit' modifier is not allowed on properties of primitive types - Kotlin

尝试将环境变量值分配给lateinit变量时出现错误。 错误是“基本类型的属性上不允许使用'lateinit'修饰符”

我的application.properties(读取环境变量)

my.property.from.properties.file=true

MyService类:

@Component
class MyService @Autowired constructor(
    private val someService: SomeService) {

    @Value("\${my.property.from.properties.file}")
    private lateinit var myBooleanEnabled: Boolean

给它分配值不能解决问题。 例如,

private lateinit var myBooleanEnabled: Boolean = true

我收到2个错误:

  • 基本类型的属性上不允许使用“ lateinit”修饰符
  • 带有初始值设定项的属性上不允许使用“ lateinit”修饰符

对于我阅读的内容,我需要一个Delegated( https://kotlinlang.org/docs/reference/delegated-properties.html ),但是我无法完全掌握它。 另外,如果有“更清洁”的解决方案,我也不必编写其他方法来设置属性。 有任何想法吗?

最简单的事情是将myBooleanEnabled定义为可为空,并删除lateinit

private var myBooleanEnabled: Boolean? = null

在这种情况下,它将不会被解释为字节码中的原始boolean

但是,根据您的情况,建议使用构造函数注入。

您可以使用构造函数注入,如下所示。 如果您使用的是Spring 4.3+,则不需要@Autowired批注。 Spring文档对此有一些指导:

https://docs.spring.io/spring/docs/current/spring-framework-reference/languages.html#injecting-dependencies

@Component
class MyService(
    private val someService: SomeService,
    @Value("\${my.property.from.properties.file}")
    private val myBooleanEnabled: Boolean)

暂无
暂无

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

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