Video in progress

Strong Middle 🌱 Spring

Which mechanism do you pick to run something once after the application has started?

ApplicationRunner/CommandLineRunner or @EventListener(ApplicationReadyEvent.class). They're called after the context is fully up, with transactions and proxies already in place. @PostConstruct is too early for this kind of work.

📖 Answer

@Component
class WarmUp implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) {
        catalog.loadPopularIntoCache();
    }
}

@Component
class SeedData {
    @EventListener(ApplicationReadyEvent.class)
    @Transactional
    public void seed() {
        if (roles.count() == 0) roles.saveAll(defaultRoles());
    }
}

The differences:

  • ApplicationRunner/CommandLineRunner — called inside SpringApplication.run. If one of them throws, the app doesn't start. Ordered with @Order.
  • ApplicationReadyEvent — after the runners, once the app is ready to take requests.

In prod these issues come up:

  • Multiple instances. 3 pods — the seed runs 3 times. Make it idempotent (if not exists) or run it on a single instance with a database lock.
  • Long work delays startup and readiness. If the Kubernetes startup probe deadline runs out, it keeps restarting the pod. Move long work to a background thread.
  • Data migrations need Flyway, not a runner: it's versioned and runs each migration exactly once.