1 問題描述
用Kotlin
編寫Spring Boot
,在業務層中使用@Transactional
+@Autowired
時出現如下錯誤:
lateinit property dao has not been initialized
出錯代碼如下:
2 解決辦法
因為Kotlin
類默認是final
的,加上@Transactional
后編譯器提示需要open
:
但是加上open
后沒用,因此把@Transactional
去掉后發現不會報錯:
因此懷疑是@Transactional
的問題,因為需要在類上加上open
,所以嘗試性地在對應的方法上面也加上open
:
問題得到解決。
3 原因
因為@Transactional
實際上是通過反射獲取Bean
的注解信息,利用AOP
實現的,而在Kotlin
中使用AOP
需要在類或方法上加上open
。