Using Generic Spring Boot Events

Using Spring Events can be very handy to decouple code. But have you ever tried creating generic events and then write a listener for them? Java or Kotlin themselves don’t prevent you from doing so but when you try receiving the events you will see that it doesn’t work. The reason for this is type erasure. Generics are being removed during compilation.

Here a simple code sample for generic Crud events in a JPA application:

open class CrudEvent<ID : Serializable, T : AbstractEntity<ID>>

fun onEvent(event: CrudEvent<UUID, User>) {}

Looks good, right? But doesn’t work. You could replace CrudEvent<UUID, User> with CrudEvent<*, *> and it would start receiving events. But of course all and not just for User. Here a simple way to get around this problem:

class UserEvent: CrudEvent<UUID, User>

fun onEvent(event: UserEvent) {}