无法在Kotlin中创建Spring Data Event Listener

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

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

。 。 。 但它不会编译。 如果指定了genericstypes,那么编译器将返回:

 Type argument expected 

我究竟做错了什么?

问题是有几个可能的BeforeSaveEvent类可以使用。 下面是一些Spring类的嘲笑,告诉你的差异( 注意两个BeforeSaveEvent声明 ):

 open class ApplicationEvent(source: Any): EventObject(source) {} interface ApplicationListener { fun onApplicationEvent(event: T) } // the Spring Data Neo4j version requires a type class BeforeSaveEvent(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 { return object : ApplicationListener { override fun onApplicationEvent(event: BeforeSaveEvent) { //Do something with event } } } } 

如果你编码到Neo4j版本(我认为你是因为你的问题的标签包含spring-data-neo4j-4 ),你还必须指定实体types参数:

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

所以你明白了编译器的要求:

请给我一个BeforeSaveEvent的types参数,因为它确实是BeforeSaveEvent

这可能是因为你导入了错误的类,意味着另一个BeforeSaveEvent或者你导入了正确的BeforeSaveEvent并且不适应它的实际genericstypes参数需求。

另外,由于ApplicationListener是一个接口,因此它在使用后不需要() ,因为这意味着您正尝试在接口上调用构造函数。

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

不知道你想达到什么,但一个简单的修复将是在返回语句中添加object关键字:

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

object意味着你返回该类的一个对象,而不是在你的代码中的东西。 另外我加了override因为我怀疑onApplicationEventApplicationListener一个方法,所以它必须被覆盖。

实际上,如果你只有一个这样的对象是可以的,你可以直接使用object作为单例:

 @Bean object beforeSaveEventApplicationListener: ApplicationListener() { override fun onApplicationEvent(event: BeforeSaveEvent) { //Do something with event } }