DEV Community

nk sk
nk sk

Posted on

πŸš€ Understanding the Spring Application Lifecycle

When you start a Spring Boot application, a lot happens behind the scenes before your code is ready to serve requests.
Just like beans have a lifecycle, the application itself goes through a well-defined sequence of events.

By understanding the Spring Application Lifecycle, you gain better control over initialization, startup, and graceful shutdown.


πŸ”„ The Spring Application Lifecycle (High-Level)

When you run a Spring Boot app (e.g., via SpringApplication.run()), the following stages occur:

  1. Bootstrap Phase
  • SpringApplication instance is created.
  • Application listeners and initializers are prepared.
  1. Environment Preparation
  • Configuration properties (from .properties, .yml, environment variables, command-line args, etc.) are loaded.
  • Profiles (e.g., dev, prod) are activated.
  1. ApplicationContext Creation
  • The ApplicationContext (IoC container) is created.
  • Bean definitions are loaded but not yet initialized.
  1. ApplicationContext Refresh
  • Beans are instantiated, dependencies injected, and lifecycle methods triggered (the bean lifecycle we discussed earlier).
  • CommandLineRunner and ApplicationRunner beans are executed.
  1. Application Ready
  • ApplicationReadyEvent is published.
  • The app is now fully up and running.
  1. Shutdown Phase
  • On JVM shutdown (e.g., CTRL+C, or SIGTERM in containers), Spring performs cleanup:

    • Calls @PreDestroy / destroy() methods on beans.
    • Closes the application context.
    • Publishes ContextClosedEvent.

πŸ“‘ Application Lifecycle Hooks

Spring provides multiple ways to hook into this lifecycle.

1. Application Events

Spring publishes events at different stages. You can listen to them:

@Component
public class MyAppEventsListener {

    @EventListener(ApplicationStartingEvent.class)
    public void onStart() {
        System.out.println("πŸš€ Application is starting...");
    }

    @EventListener(ApplicationReadyEvent.class)
    public void onReady() {
        System.out.println("βœ… Application is ready!");
    }

    @EventListener(ContextClosedEvent.class)
    public void onShutdown() {
        System.out.println("πŸ›‘ Application is shutting down...");
    }
}
Enter fullscreen mode Exit fullscreen mode

2. CommandLineRunner and ApplicationRunner

Run code right after the application context is ready.

@Component
public class StartupRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        System.out.println("πŸƒ Running startup logic...");
    }
}
Enter fullscreen mode Exit fullscreen mode

ApplicationRunner is similar but gives you ApplicationArguments instead of raw String[].

3. SmartLifecycle

For beans that need start/stop callbacks.

@Component
public class MyLifecycleBean implements SmartLifecycle {

    private boolean running = false;

    @Override
    public void start() {
        System.out.println("▢️ Custom lifecycle bean started");
        running = true;
    }

    @Override
    public void stop() {
        System.out.println("⏹ Custom lifecycle bean stopped");
        running = false;
    }

    @Override
    public boolean isRunning() {
        return running;
    }
}
Enter fullscreen mode Exit fullscreen mode

4. DisposableBean / PreDestroy

During shutdown, Spring ensures resources are released:

@Component
public class ShutdownHook {

    @PreDestroy
    public void cleanup() {
        System.out.println("🧹 Cleaning up resources before shutdown...");
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Š Visualizing the Application Lifecycle

[SpringApplication Bootstrap]
        ↓
[Environment Prepared]
        ↓
[ApplicationContext Created]
        ↓
[Beans Initialized & Context Refreshed]
        ↓
[CommandLineRunner / ApplicationRunner Executed]
        ↓
[ApplicationReadyEvent Published β†’ App Running]
        ↓
[ContextClosedEvent Published β†’ Shutdown Hooks]
Enter fullscreen mode Exit fullscreen mode

πŸ”Ž Comparison of Lifecycle Hooks

Hook Type When It Runs Common Use Case
ApplicationStartingEvent At very start, before context created Logging setup, metrics init
ApplicationReadyEvent After startup is complete Notify external systems, warm-up caches
CommandLineRunner / ApplicationRunner After context refresh, before ready Startup logic, data seeding
@PreDestroy / DisposableBean Before shutdown Resource cleanup
SmartLifecycle Start/stop custom beans Manage background tasks

πŸ“ Conclusion

The Spring Application Lifecycle ensures a smooth flow from startup β†’ running β†’ shutdown.

  • Use Application Events to react to key stages.
  • Use CommandLineRunner or ApplicationRunner for startup logic.
  • Use @PreDestroy or SmartLifecycle for graceful shutdown.

By combining bean lifecycle hooks with the application lifecycle, you can build applications that are robust, predictable, and resource-safe.


Top comments (0)