Complete the code to publish an event using Spring Boot's ApplicationEventPublisher.
applicationEventPublisher.[1](new CustomEvent(this, "Hello"));
In Spring Boot, publishEvent is the method used to send events.
Complete the code to listen for events using @EventListener annotation.
@EventListener
public void handleEvent([1] event) {
System.out.println(event.getMessage());
}The method parameter should be the specific event class you want to listen to, here CustomEvent.
Fix the error in the event class by completing the constructor correctly.
public class CustomEvent extends ApplicationEvent { private final String message; public CustomEvent(Object source, String message) { super([1]); this.message = message; } public String getMessage() { return message; } }
The superclass constructor requires the source object, so pass source.
Fill both blanks to create a listener method that listens asynchronously and logs the event message.
@Async @EventListener public void onEvent([1] event) { logger.[2]("Received: " + event.getMessage()); }
The listener method should accept CustomEvent and use logger.info to log the message.
Fill all three blanks to define a Spring Boot event publisher bean and publish an event inside it.
import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; @Component public class EventPublisher { private final ApplicationEventPublisher [1]; public EventPublisher(ApplicationEventPublisher [2]) { this.[3] = [2]; } public void publish(String message) { [1].publishEvent(new CustomEvent(this, message)); } }
The standard name used is applicationEventPublisher for clarity and consistency.