jav*_*dev 3 java spring spring-mvc spring-annotations
我正在尝试在Spring MVC中发布自定义事件,但在加载上下文时未触发,下面是代码段,
连接到服务器后将调用onConnectionOpened,该服务器是在使用@PostConstruct进行bean初始化之后触发的
@Autowired
private ApplicationEventPublisher publisher;
public void onConnectionOpened(EventObject event) {
publisher.publishEvent(new StateEvent("ConnectionOpened", event));
}
Run Code Online (Sandbox Code Playgroud)
我在侦听器部分中使用注释,如下所示
@EventListener
public void handleConnectionState(StateEvent event) {
System.out.println(event);
}
Run Code Online (Sandbox Code Playgroud)
我能够看到在加载或刷新上下文后触发的事件,这是否可以在加载或刷新上下文后发布自定义应用程序事件?
我正在使用Spring 4.3.10
提前致谢
该@EventListener注释被处理EventListenerMethodProcessor为所有的bean被实例化,并准备将立即运行。当您从带@PostConstruct注释的方法发布事件时,可能不是当时所有内容@EventListener都已启动并正在运行,并且尚未检测到基于方法。
相反,您可以使用ApplicationListener界面来获取事件并进行处理。
public class MyEventHandler implements ApplicationListener<StateEvent> {
public void onApplicationEvent(StateEvent event) {
System.out.println(event);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
788 次 |
| 最近记录: |