Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not able to publish custom event in spring before context load

I am trying to publish a custom event in Spring MVC, but is is not firing while context is loading, below are the code snippet,

The onConnectionOpened will be called after connecting to a server which is triggered after bean initialization using @PostConstruct

@Autowired
private ApplicationEventPublisher publisher;

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

}

I am using annotation in listener part as below

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

I am able to see events fired after the context is loaded or refreshed, is this expected that custom application events can be published after the context loaded or refreshed?.

I am using Spring 4.3.10

Thanks in advance

like image 327
java_dev Avatar asked Oct 28 '25 03:10

java_dev


1 Answers

The @EventListener annotations are processed by the EventListenerMethodProcessor which will run as soon as all beans are instantiated and ready. As you are publishing an event from a @PostConstruct annotated method it might be that not everything is up and running at that moment and @EventListener based methods haven't been detected yet.

Instead what you can do is use the ApplicationListener interface to get the events and process them.

public class MyEventHandler implements ApplicationListener<StateEvent> {

    public void onApplicationEvent(StateEvent event) {
        System.out.println(event);
    }
}       
like image 77
M. Deinum Avatar answered Oct 29 '25 17:10

M. Deinum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!