原文地址: 关于使用Kotlin开发SpringBoot项目使用@Transactional和@Autowired的报错问题 - Stars-One的杂货小窝
问题描述
最近在开发一个订单模块,需要出现异常就会触发数据回滚操作,首先就是想到了Spring Boot提供的@Transactiona
注解功能,但是使用的时候,发现其他方法就是出现了lateinit property xx has not been initialized
的错误
代码如下:
@RequestMapping("/testPay")
@RestController
open class PayController {
@Autowired
lateinit var xnGoodService: XnGoodService
@GetMapping("test")
@ResponseBody
fun test(): AjaxJson {
//这里会报错!! lateinit property xnGoodService has not been initialized
val good = xnGoodService.getById("62479fb79d6f461b92d80c")
println(good)
return AjaxJson.getSuccess()
}
@RequestMapping("confirmOrder")
@ResponseBody
@Transactional(rollbackFor = [Exception::class])
open fun confirmOrder(@RequestBody json: String): String {
...
}
}
解决方案
解决方法很简单,由于kotlin默认类都是final类型,当你要使用@Transactional
注解,需要将当前类用open关键字声明,同时要将类里的所有方法都用open关键字声明
上面的test方法里就是因为没有open声明,才会导致报错了
参考
- Transactional SpringBoot Autowired 项目 Kotlintransactional springboot autowired项目 注解springboot autowired项目 springboot candidates autowired matching springframework springboot annotation autowired transactional springboot2 springboot springboot autowired属性 springboot autowired nullpoint单元 invocationhandler springboot autowired springboot autowired resource transactional springboot场景