Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 66 ยท Inversion of Control and Beans

Application Events and Runners

Run code at startup with ApplicationRunner and CommandLineRunner, react to ApplicationReadyEvent, publish custom events and order @EventListener methods.

Applications need to react to things: "the app has started, load the cache", "an order was placed, send an email and update stock". Wiring each reaction as a direct method call makes classes know about each other. Spring offers two clean tools instead. Runners execute code once at startup, and events let one component announce something while any number of others listen, without the publisher knowing who they are.

This lesson covers CommandLineRunner and ApplicationRunner, the events Boot publishes during startup, custom events with @EventListener, ordering, and the pitfalls (listeners are synchronous by default). Real Spring code is read-only; the TryIts are plain-Java stand-ins that model the mechanism and say what is imitation.

Two tools for "do something when..."

Runners Code that runs once, right after startup.
Events Announce a fact. Anyone can listen.

Runners are for the app lifecycle, events for things that happen inside it.

1 / 2

Runners: code that runs at startup

A runner is a bean whose method Boot calls once, after the application context is fully built and (in a web app) the server is accepting connections. There are two interfaces, differing only in how they present the command-line arguments:

Java
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
class CacheWarmer implements CommandLineRunner {

    @Override
    public void run(String... args) {
        // args is the raw String[] from main
    }
}

@Component
class Seeder implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        boolean demo = args.containsOption("demo");           // --demo
        List<String> files = args.getNonOptionArgs();          // plain arguments
    }
}

ApplicationRunner parses the arguments for you: --name=value becomes an option and everything else is a non-option argument. Both can also be declared as a @Bean returning a lambda.

If several runners exist, order them with @Order (lower first) or by implementing Ordered:

Java
@Component @Order(1) class SchemaCheck implements ApplicationRunner { ... }
@Component @Order(2) class DemoData implements ApplicationRunner { ... }

Two things to remember. Runners run before Boot reports "ready", and they run on the main thread, so a slow runner delays readiness probes and traffic. And an exception thrown from a runner stops the whole application, which is useful for "fail fast" checks and a nasty surprise for anything optional. Catch and log exceptions in runners that are not essential.

When a one-time job is not about the application's life, such as seeding data in production, prefer a proper migration tool (Database Migrations with Flyway) over a runner that runs on every start.

The events Boot publishes

Boot announces its progress with events. Listening to the right one is the clean way to hook into a precise moment. These are the main ones, in order:

sequenceDiagram
    participant App as SpringApplication
    participant L as Your listeners
    App->>L: ApplicationStartingEvent
    App->>L: ApplicationEnvironmentPreparedEvent
    App->>L: ApplicationPreparedEvent
    Note over App: context refresh, beans created
    App->>L: ContextRefreshedEvent
    App->>L: ApplicationStartedEvent
    App->>App: run ApplicationRunner and CommandLineRunner beans
    App->>L: ApplicationReadyEvent

The first events fire before the context exists; the last two bracket the runners.

The earliest events are published before the context exists, so ordinary beans cannot listen to them. They exist for framework extensions registered in META-INF/spring.factories or added to the SpringApplication. For your own code the useful ones are:

  • ApplicationStartedEvent: the context is refreshed, runners have not run yet.
  • ApplicationReadyEvent: runners are done and the app is ready to serve requests. This is the right place for "the app is up" work such as warming caches or registering with a service registry.
  • ApplicationFailedEvent: startup failed.
Java
@Component
class StartupNotifier {

    @EventListener(ApplicationReadyEvent.class)
    void onReady() {
        log.info("Shop is ready");
    }
}

Custom events and @EventListener

Since Spring 4.2 an event can be any object: a plain record works. You publish through ApplicationEventPublisher (which a component can simply inject) and listen with @EventListener. The method parameter's type decides which events it receives.

Java
public record OrderPlaced(long orderId, String email, int totalCents) {}

@Service
class OrderService {
    private final ApplicationEventPublisher events;

    OrderService(ApplicationEventPublisher events) {
        this.events = events;
    }

    void place(Order order) {
        // ... save the order
        events.publishEvent(new OrderPlaced(order.id(), order.email(), order.total()));
    }
}

@Component
class ConfirmationMailer {
    @EventListener
    void on(OrderPlaced event) { /* send mail to event.email() */ }
}

@Component
class StockUpdater {
    @EventListener
    @Order(10)
    void on(OrderPlaced event) { /* reduce stock */ }
}

OrderService knows nothing about mail or stock. Adding an analytics reaction means writing one new component and touching nothing else. Listener parameter types are matched through inheritance, so a method taking a superclass or an interface also receives subclasses. A listener may also return a value: if it does, the returned object is published as a new event, which lets you chain steps.

Ordering

When several listeners handle the same event, @Order(n) controls the order (lower values first, and the default is "last"). Do not depend on ordering for correctness more than you must; if step B truly needs step A, call them in sequence from one place instead.

Synchronous by default

This is the part that surprises people: listeners run in the publisher's thread, one after another. publishEvent returns only when every listener has finished. Three consequences follow.

  • A slow listener slows the publisher. A request that places an order also waits for the email.
  • An exception in a listener propagates to the publisher and can abort the operation.
  • If the publisher is inside a transaction, the listener runs inside it too.

Two fixes exist. @Async on the listener (with @EnableAsync) moves it to another thread, at the cost of losing the caller's transaction and exception propagation (Scheduling and Asynchronous Work). And @TransactionalEventListener delays the listener until the surrounding transaction commits (the default phase is AFTER_COMMIT), which prevents sending an email for an order that was later rolled back. The mechanism is explained in Events and Transactions in Spring.

The first TryIt is a small event bus. Its listeners are found by reflection (our own @Listener annotation), matched by the parameter's type, and ordered.

Java An event bus stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: listeners chosen by event type, ordered, called synchronously before publish returns. What is the stand-in: no ApplicationContext, no @Async, transactions or generics-aware matching.

Startup order in one picture

The second TryIt puts the startup pieces together: events, then runners in @Order, then the ready event. It also shows what a failing runner does to the whole startup.

Java Startup sequence: events and ordered runners

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A failing runner means the ready event never fires. In real Boot the failure is reported with a stack trace and a non-zero exit code, and ApplicationFailedEvent is published to listeners that were registered early enough to hear it.

Choosing the right tool

  • Needs to run once after startup, such as a warm-up or a startup check: a runner, or @EventListener(ApplicationReadyEvent.class) when you want to run after every runner.
  • Something happened in your domain and several parts care: a custom event with @EventListener.
  • Must wait for a transaction commit: @TransactionalEventListener.
  • Must not slow down the publisher: @Async, or a message queue when the work must survive crashes (Messaging and Events Between Services). In-process events are lost if the application dies, so never use them as the only record of something important.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between CommandLineRunner and ApplicationRunner?

    Both run after the context is ready. ApplicationRunner gets arguments parsed into options and non-option arguments, while CommandLineRunner gets the raw array.
  2. 2. When is ApplicationReadyEvent published relative to the runners?

    ApplicationStartedEvent comes before the runners, and ApplicationReadyEvent comes after they complete, signalling that the app is ready for traffic.
  3. 3. A @EventListener method throws an exception. What happens by default?

    Listeners run in the publisher's thread, so an exception comes straight back to publishEvent and may abort the operation unless you handle it or make the listener asynchronous.
  4. 4. Why use @TransactionalEventListener for an order confirmation email?

    With its default AFTER_COMMIT phase, the listener runs only once the transaction has actually committed.

Summary

  • CommandLineRunner and ApplicationRunner beans run once after startup, ordered with @Order; a failing runner stops the application.
  • Boot publishes lifecycle events; ApplicationStartedEvent comes before the runners, ApplicationReadyEvent after them.
  • Any object can be an event: publish it with ApplicationEventPublisher and handle it with @EventListener, which matches by parameter type.
  • Listeners are synchronous by default and share the publisher's thread and transaction; use @Async or @TransactionalEventListener when you need otherwise.
  • In-process events are not durable, so use a message broker for work that must survive a crash.

Next: How Auto-Configuration Works.