Skip to content

Commit 06a0dfa

Browse files
committed
Update ApplicationEvent doc for generics event
Issue: SPR-13069
1 parent ea9d7aa commit 06a0dfa

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/asciidoc/core-beans.adoc

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7851,6 +7851,58 @@ This new method will publish a new `ListUpdateEvent` for every `BlackListEvent`
78517851
by the method above. If you need to publish several events, just return a `Collection` of
78527852
events instead.
78537853

7854+
[[context-functionality-events-generics]]
7855+
==== Generic Events
7856+
7857+
You may also use generics to further define the structure of your event. Consider an
7858+
`EntityCreatedEvent<T>` where `T` is the type of the actual entity that got created. You
7859+
can create the following listener definition to only receive `EntityCreatedEvent` for a
7860+
`Person`:
7861+
7862+
[source,java,indent=0]
7863+
[subs="verbatim,quotes"]
7864+
----
7865+
@EventListener
7866+
public void onPersonCreated(EntityCreatedEvent<Person> event) {
7867+
...
7868+
}
7869+
----
7870+
7871+
7872+
Due to type erasure, this will only work if the event that is fired resolves the generic
7873+
parameter(s) on which the event listener filters on (that is something like
7874+
`class PersonCreatedEvent extends EntityCreatedEvent<Person> { ... }`).
7875+
7876+
In certain circumstances, this may become quite tedious if all events follow the same
7877+
structure (as it should be the case for the event above). In such a case, you can
7878+
implement `ResolvableTypeProvider` to _guide_ the framework beyond what the runtime
7879+
environment provides:
7880+
7881+
[source,java,indent=0]
7882+
[subs="verbatim,quotes"]
7883+
----
7884+
public class EntityCreatedEvent<T>
7885+
extends ApplicationEvent implements ResolvableTypeProvider {
7886+
7887+
public EntityCreatedEvent(T entity) {
7888+
super(entity);
7889+
}
7890+
7891+
@Override
7892+
public ResolvableType getResolvableType() {
7893+
return ResolvableType.forClassWithGenerics(getClass(),
7894+
ResolvableType.forInstance(getSource()));
7895+
}
7896+
}
7897+
----
7898+
7899+
[TIP]
7900+
====
7901+
This works not only for `ApplicationEvent` but any arbitrary object that you'd send as
7902+
an event.
7903+
====
7904+
7905+
78547906

78557907
[[context-functionality-resources]]
78567908
=== Convenient access to low-level resources

0 commit comments

Comments
 (0)