[英]'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個錯誤:
對於我閱讀的內容,我需要一個Delegated( https://kotlinlang.org/docs/reference/delegated-properties.html ),但是我無法完全掌握它。 另外,如果有“更清潔”的解決方案,我也不必編寫其他方法來設置屬性。 有任何想法嗎?
最簡單的事情是將myBooleanEnabled
定義為可為空,並刪除lateinit
private var myBooleanEnabled: Boolean? = null
在這種情況下,它將不會被解釋為字節碼中的原始boolean
。
但是,根據您的情況,建議使用構造函數注入。
您可以使用構造函數注入,如下所示。 如果您使用的是Spring 4.3+,則不需要@Autowired
批注。 Spring文檔對此有一些指導:
@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.