gpt4 book ai didi

spring - Spring 代理类和 Kotlin 中的空指针异常

转载 作者:IT老高 更新时间:2023-10-28 13:41:31 24 4
gpt4 key购买 nike

我在将 kotlin 与 spring 结合使用时遇到了一些问题。

我有一个 Controller bean(顺便说一句,没有接口(interface)),它通过主构造函数有一个自动连接的服务 bean。

除非我为 Controller 使用缓存注释,否则它工作得很好。显然 springs 缓存会在后台生成一个代理类来处理缓存。

我的代码如下所示:

@RestController
@RequestMapping("/regions/")
open class RegionController @Autowired constructor(val service: RegionService) {
@RequestMapping("{id}", method = arrayOf(RequestMethod.GET))
@Cacheable(cacheNames = arrayOf("regions"))
fun get(@PathVariable id: Long): RegionResource {
return this.service.get(id)
}
}

现在的问题是执行方法时出现空指针异常,实际上 this.servicenull 这在技术上是不可能的,因为它是 kotlin 中的非空变量.

我假设 class proxies generated by spring用空值而不是 Autowiring 的 bean 来初始化类。这一定是使用 kotlin 和 spring 的常见陷阱。你是如何规避这个问题的?

最佳答案

在 Kotlin 中,classes and members are final默认情况下。

为了让代理库(CGLIBjavaassist)能够代理一个方法,它必须声明为 non final 并且在 non final 类中(since those libraries implement proxying by subclassing)。将 Controller 方法更改为:

@RequestMapping("{id}", method = arrayOf(RequestMethod.GET))
@Cacheable(cacheNames = arrayOf("regions"))
open fun get(@PathVariable id: Long): RegionResource {
return this.service.get(id)
}

您可能会在控制台中看到关于 RegionController 方法不受代理影响的警告。

The Kotlin compiler plugin

Kotlin 团队已经认识到这一困难,并创建了一个插件来标记标准 AOP 代理候选者,例如@Componentopen

您可以在 build.gradle 中启用插件:

plugins {
id "org.jetbrains.kotlin.plugin.spring" version "1.1.60"
}

关于spring - Spring 代理类和 Kotlin 中的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com