gpt4 book ai didi

java - 无法在 Kotlin 中创建 Spring Data 事件监听器

转载 作者:行者123 更新时间:2023-12-01 22:02:56 25 4
gpt4 key购买 nike

我尝试创建一个像这样的事件监听器:

@Bean
open fun beforeSaveEventApplicationListener(): ApplicationListener<BeforeSaveEvent>
{
return ApplicationListener<BeforeSaveEvent>()
{
fun onApplicationEvent(event: BeforeSaveEvent)
{
//Do something with event
}
}
}

。 。 。但它不会编译。在指定泛型类型的情况下,编译器返回:

Type argument expected

我做错了什么?

最佳答案

问题是有几种可能的 BeforeSaveEvent您可能正在使用的类(class)。下面是一些模拟出来的 Spring 类,以向您展示差异(注意两个 BeforeSaveEvent 声明):

open class ApplicationEvent(source: Any): EventObject(source) {}

interface ApplicationListener<T: ApplicationEvent> {
fun onApplicationEvent(event: T)
}

// the Spring Data Neo4j version requires a type
class BeforeSaveEvent<T>(source: Any, val entity: T): ApplicationEvent(source) {}

// the Spring data version does not
class BeforeSaveEvent(source: Any): ApplicationEvent(source) {}

因此,如果您编写 Spring 数据版本的代码,您的代码将是这样的:

open class Something {
open fun beforeSaveEventApplicationListener(): ApplicationListener<BeforeSaveEvent> {
return object : ApplicationListener<BeforeSaveEvent> {
override fun onApplicationEvent(event: BeforeSaveEvent) {
//Do something with event
}
}
}
}

如果您编码为 Neo4j 版本(我认为您是这样,因为您问题的标签包括 spring-data-neo4j-4 ),您还必须指定实体类型参数:

class MyEntity {}

open class Something {
open fun beforeSaveEventApplicationListener(): ApplicationListener<BeforeSaveEvent<MyEntity>> {
return object : ApplicationListener<BeforeSaveEvent<MyEntity>> {
override fun onApplicationEvent(event: BeforeSaveEvent<MyEntity>) {
//Do something with event
}
}
}
}

因此您可以准确地看到编译器的要求:

Please give me a type parameter for BeforeSaveEvent because it is really BeforeSaveEvent<T>

可能是您导入了错误的类,并且指的是其他 BeforeSaveEvent或者您导入了正确的 BeforeSaveEvent<T>并且没有适应其实际的泛型类型参数需求。

也是从ApplicationListener开始是您不想要的界面 ()在使用它之后,因为这意味着您正在尝试调用接口(interface)上的构造函数。

注意: 从 IDE 的角度来看,提供相关类的声明签名会有助于解决您的问题(点击它即可找到您要查找的类)正在使用,它可能不是您认为的那个)。

关于java - 无法在 Kotlin 中创建 Spring Data 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33419480/

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