In my previous post, I wrote about running infinite loop in Java and also I mention that it was not recommended way of doing and wrote an alternate way with Spring boot scheduling, read here.
In this blog lets see how we can achieve with the ApplicationReadyEvent in SpringBoot
Create a class implementing the org.springframework.context.ApplicationListener and implement the business logic in the Override method onApplicationEvent
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class ProcessMessage implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
service.start();
while (service.isRunning()){
service.waitForMessage();
service.processMessage();
}
service.stop();
}
}
Also published on Medium.