Complete the code to inject ApplicationEventPublisher in a Spring component.
public class MyComponent { private final ApplicationEventPublisher [1]; public MyComponent(ApplicationEventPublisher publisher) { this.publisher = publisher; } }
The variable name for ApplicationEventPublisher is commonly publisher to keep code clear and simple.
Complete the code to publish a custom event using ApplicationEventPublisher.
public void publishEvent(String message) {
MyCustomEvent event = new MyCustomEvent(this, message);
[1].publishEvent(event);
}The publisher variable is used to call publishEvent method to send the event.
Fix the error in the event class constructor to properly extend ApplicationEvent.
public class MyCustomEvent extends ApplicationEvent { private final String message; public MyCustomEvent([1] source, String message) { super(source); this.message = message; } public String getMessage() { return message; } }
The constructor must accept an Object as the source parameter to pass to the superclass ApplicationEvent.
Fill both blanks to create and publish a new event with a message.
public void sendMessage(String msg) {
[1] event = new MyCustomEvent(this, msg);
[2].publishEvent(event);
}First, create an instance of MyCustomEvent. Then use the publisher variable to publish it.
Fill all three blanks to define a Spring component that publishes an event with a message.
@Component public class EventPublisher { private final [1] publisher; public EventPublisher([2]) { this.publisher = eventPublisher; } public void publish(String msg) { [3] event = new MyCustomEvent(this, msg); publisher.publishEvent(event); } }
The field is declared as ApplicationEventPublisher. The constructor parameter is named eventPublisher of type ApplicationEventPublisher. The event variable is of type MyCustomEvent.