[英]'lateinit' modifier is not allowed on properties of primitive types - Kotlin
I'm getting an error while trying to assign a environment variable value to a lateinit
variable. 尝试将环境变量值分配给lateinit
变量时出现错误。 The error is "'lateinit' modifier is not allowed on properties of primitive types" . 错误是“基本类型的属性上不允许使用'lateinit'修饰符” 。
My application.properties (reading the environment variable) 我的application.properties(读取环境变量)
my.property.from.properties.file=true
MyService class: MyService类:
@Component
class MyService @Autowired constructor(
private val someService: SomeService) {
@Value("\${my.property.from.properties.file}")
private lateinit var myBooleanEnabled: Boolean
Assigning a value to it does not solve the problem. 给它分配值不能解决问题。 For example, with 例如,
private lateinit var myBooleanEnabled: Boolean = true
I get 2 errors: 我收到2个错误:
For what I read, I need a Delegated ( https://kotlinlang.org/docs/reference/delegated-properties.html ) but I could not grasp it fully. 对于我阅读的内容,我需要一个Delegated( https://kotlinlang.org/docs/reference/delegated-properties.html ),但是我无法完全掌握它。 Also, I don't want to have to write another method to set the property if there is a "cleaner" solution. 另外,如果有“更清洁”的解决方案,我也不必编写其他方法来设置属性。 Any ideas? 有任何想法吗?
The simplest thing is to define myBooleanEnabled
as nullable and remove lateinit
最简单的事情是将myBooleanEnabled
定义为可为空,并删除lateinit
private var myBooleanEnabled: Boolean? = null
In this case, it will not be interpreted as a primitive boolean
in bytecode. 在这种情况下,它将不会被解释为字节码中的原始boolean
。
However, in your case, I'd suggest a constructor injection. 但是,根据您的情况,建议使用构造函数注入。
You can use constructor injection as shown below. 您可以使用构造函数注入,如下所示。 If you're using Spring 4.3+ you don't need the @Autowired
annotation. 如果您使用的是Spring 4.3+,则不需要@Autowired
批注。 Spring documentation has some guidelines on this: Spring文档对此有一些指导:
https://docs.spring.io/spring/docs/current/spring-framework-reference/languages.html#injecting-dependencies 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.