上下文加载前无法在 spring 中发布自定义事件

not able to publish custom event in spring before context load

我正在尝试在 Spring MVC 中发布自定义事件,但在加载上下文时未触发,下面是代码片段,

onConnectionOpened 将在连接到使用@PostConstruct 初始化bean 后触发的服务器后调用

@Autowired
private ApplicationEventPublisher publisher;

public void onConnectionOpened(EventObject event) {
    publisher.publishEvent(new StateEvent("ConnectionOpened", event));

}

我在下面的侦听器部分使用注释

@EventListener
public void handleConnectionState(StateEvent event) {
   System.out.println(event);
}

我能够看到加载或刷新上下文后触发的事件,这是否预期可以在加载或刷新上下文后发布自定义应用程序事件?

我正在使用 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);
    }
}       

你应该在ContextRefreshedEvent发生后发布事件,但是如果你在@PostConstruct中等待ContextRefreshedEvent,它会使整个应用程序挂起,所以使用@Async可以解决这个问题。

@EnableAsync
@SpringBootApplication
public class YourApplication
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}
@Slf4j
@Service
public class PublishHelper {
    private final ApplicationEventPublisher publisher;

    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    @EventListener(classes = {ContextRefreshedEvent.class})
    public void eventListen(ContextRefreshedEvent contextRefreshedEvent) {
        log.info("publish helper is ready to publish");
        countDownLatch.countDown();
    }

    public PublishHelper(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    @Async
    @SneakyThrows
    public void publishEvent(Object event) {
        countDownLatch.await();
        publisher.publishEvent(event);
    }
}