Step 1: Set up a Spring Boot project
Step 2: Create a custom event (plain java object). implementation with ApplicationEvent
(marker class).
public class MyCustomEvent extends ApplicationEvent {
private String message;
public MyCustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
Step 3: Create an event publisher (spring bean with method). use ApplicationEventPublisher
or ApplicationContext
.
@Service
public class MyEventPublisher implements InitializingBean {
private final ApplicationEventPublisher eventPublisher;
public MyEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void publishEvent(String message) {
MyCustomEvent event = new MyCustomEvent(this, message);
eventPublisher.publishEvent(event);
}
// Add test event handling
@Override
public void afterPropertiesSet() {
// Publish the custom event
eventPublisher.publishEvent("Hello, world!");
}
}
Step 4: Create an event listener (spring bean). Annotate a method within this class with the @EventListener
annotation, specifying the event type that the method should handle.
@Component
public class MyEventListener {
@EventListener
public void handleCustomEvent(MyCustomEvent event) {
System.out.println("Received custom event: " + event.getMessage());
// Handle the event logic here
}
}