Run Code on Spring Startup

@Component
public class EventListenerExampleBean {

    private static final Logger LOG 
      = Logger.getLogger(EventListenerExampleBean.class);

    public static int counter;

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        LOG.info("Increment counter");
        counter++;
    }
}

We can use this approach for running logic after the Spring context has been initialized. So, we aren’t focusing on any particular bean. We’re instead waiting for all of them to initialize.

We want to make sure to pick an appropriate event for our needs. In this example, we chose the ContextRefreshedEvent.

References
https://www.baeldung.com/running-setup-logic-on-startup-in-spring