In Spring, events can be transformed from one type to another.
We can use an non-void return type with the listener methods (methods annotated with @EventListener). We will do that if we want to publish another event at the end of processing current event.
Example
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
@Configuration
public class EventTransformingExample {
@Bean
AListenerBean listenerBean() {
return new AListenerBean();
}
@Bean
AnotherListenerBean anotherListenerBean() {
return new AnotherListenerBean();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(EventTransformingExample.class);
context.publishEvent(new MyEvent("test message 1"));
}
private static class AListenerBean {
@EventListener
public MyAnotherEvent handleContextEvent(MyEvent myEvent) {
System.out.printf("event received by %s, event: %s%n", this.getClass().getSimpleName(), myEvent);
return new MyAnotherEvent("test message 2");
}
}
private static class AnotherListenerBean {
@EventListener
public void handleContextEvent(MyAnotherEvent myEvent) {
System.out.printf("event received by %s, event: %s%n", this.getClass().getSimpleName(), myEvent);
}
}
private static class MyEvent {
private String msg;
public MyEvent(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "MyEvent{" +
"msg='" + msg + '\'' +
'}';
}
}
private static class MyAnotherEvent {
private String msg;
public MyAnotherEvent(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "MyAnotherEvent{" +
"msg='" + msg + '\'' +
'}';
}
}
}
Output
event received by AListenerBean, event: MyEvent{msg='test message 1'} event received by AnotherListenerBean, event: MyAnotherEvent{msg='test message 2'}
Example Project
Dependencies and Technologies Used:
spring-context 6.1.2 (Spring Context) Version Compatibility: 4.2.0.RELEASE - 6.1.2Version List
×
Version compatibilities of spring-context with this example: