Spring 的 ApplicationEvent 中的源是什么?

fyr*_*kov 5 java events spring

在 Spring Framework 中,表示由 发布并由are ApplicationEventPublisher侦听的事件的类。@EventListenerEventObject <- ApplicationEvent <- PayloadApplicationEvent

我的问题是source初始EventObject构造函数和所有派生子类构造函数中的不可为空是什么?

Javadocs 给出了一个相当模糊的解释,即它是
“所讨论的事件最初发生的对象”

它是关联的域实体或发布者服务还是其他什么?

此外,我很困惑,如果@EventListener声明 “事件可以是 ApplicationEvent 实例以及任意对象”,为什么还需要它?

Rob*_*ohr 3

据我所知,source这是事件创建的地方。例如,@Service处理从 接收到的 Web 请求的@Controller。因此,当您调用事件ApplicationEventPublisher.publishEvent()的源参数时,服务。ApplicationEventthis

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"));
    }
}
Run Code Online (Sandbox Code Playgroud)