In Spring Framework classes that represent an event to be published by the ApplicationEventPublisher
and listened to by the @EventListener
are EventObject <- ApplicationEvent <- PayloadApplicationEvent
.
My question is what is the non-nullable source
in the initial EventObject
constructor and all derived subclasses constructors?
Javadocs give a rather vague explanation that it is
"the object upon which the Event in question initially occurred" .
Is it an associated domain entity or publisher service or something else?
Additionally, I am confused why is it required at all if @EventListener
states that "Events can be ApplicationEvent instances as well as arbitrary objects" ?
I understand source
to be the where the event is created. For example, a @Service
that processes a web request received from a @Controller
. Therefore, when you call ApplicationEventPublisher.publishEvent()
the source parameter to the ApplicationEvent
event is this
, the service.
public class AwesomeEvent extends ApplicationEvent {
private final String howAwesome;
public AwesomeEvent(Object source, String howAwesome) {
super(source);
this.howAwesome = howAwesome;
}
}
@Service
@RequiredArgsConstructor // because, lazy
public class AwesomeService {
private final ApplicationEventPublisher eventPublisher;
public void awesomeMethod() {
// Do superhero awesome stuff
eventPublisher.publishEvent(new AwesomeEvent(this, "Extremely"));
}
}
Just show some code to you. Look at the getApplicationContext() method.
public abstract class ApplicationContextEvent extends ApplicationEvent {
public ApplicationContextEvent(ApplicationContext source) {
super(source);
}
public final ApplicationContext getApplicationContext() {
return (ApplicationContext) getSource();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.