Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

Bean background initialization in the Spring Framework provides a way to initialize selected beans asynchronously during application context startup. Instead of blocking the startup process on every bean initialization, Spring initializes selected beans in the background and continues processing the remaining application context. This improves application startup time and reduces perceived latency in applications with expensive initialization logic.

In this tutorial, we’ll explore how Bean background initialization works using the Spring native bootstrap attribute. We’ll demonstrate how to configure it correctly, how Spring manages lifecycle consistency during asynchronous initialization, and how this approach improves startup performance in real-world applications that rely on heavy resources such as caches, external services, or computation-heavy components.

2. Why Background Initialization Matters in Spring

Spring initializes singleton beans during the ApplicationContext refresh phase in a strictly synchronous manner. During startup, the container manages the complete bean lifecycle and processes each bean in sequence:

  1. bean instantiation
  2. dependency injection
  3. initialization callback execution
  4. marking the bean as ready for use

This approach provides predictable and deterministic startup behavior by ensuring that each bean reaches a fully initialized state before the context refresh proceeds. However, it introduces performance constraints when beans execute expensive operations during initialization.

2.1. Synchronous Bean Initialization Model

Expensive initialization increases the duration of the ApplicationContext refresh phase by forcing the container to complete the lifecycle of each bean before moving forward. It reduces throughput in the bean creation pipeline and increases overall startup latency. As a result, even non-critical initialization logic delays the application from becoming available.

2.2. Single-Threaded Initialization Bottleneck

The default startup model executes all bean initialization on the same thread that drives the context refresh process. Consequently, Spring executes independent initialization tasks sequentially and prevents them from running concurrently. This limits startup throughput and prevents Spring from taking advantage of available parallelism during application bootstrap.

3. Background Initialization Mechanism

Spring introduces background initialization using the bootstrap attribute to reduce startup blocking caused by expensive singleton bean creation.

During application context refresh, Spring applies a modified execution strategy to selected beans:

  • Async delegation: Spring delegates the initialization phase of selected beans to a container-managed executor (the bootstrap executor), enabling execution to occur on a separate thread without blocking the main refresh process.
  • Dependency coordination: When another bean depends on a background-initialized bean through a non-lazy dependency, Spring suspends dependency resolution for that bean and waits for initialization to complete before injecting the bean.
  • Lifecycle preservation: Spring preserves the standard lifecycle order.

This design ensures safe background execution while decoupling heavy initialization from the main startup thread, enabling earlier application readiness without affecting bean consistency.

4. Example Setup

This section introduces a product preload class that simulates an expensive startup workload in Spring applications. This can be cache warming, dataset loading, or external resource preparation, which typically increases application startup time.

Let’s define the class to demonstrate this behavior:

public class ProductCatalogInitializer {

    public ProductCatalogInitializer() {
        loadProducts();
    }

    private void loadProducts() {
        System.out.println("Starting product preload");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Product preload completed");
    }

    public String getStatus() {
        return "Catalog ready";
    }
}

The loadProducts() method represents a long-running initialization task executed during bean creation. Spring runs this logic on the main startup thread, which blocks the ApplicationContext refresh until completion.

This component acts as the baseline for demonstrating how Spring shifts such initialization work to background execution using the bootstrap mechanism in the next section.

5. Background Initialization Using Bootstrap Mode

Spring applies background initialization at the bean definition level using the bootstrap attribute. Selected beans then get initialized concurrently without blocking the main startup thread.

5.1. Enabling Background Initialization

At this point, let’s create a configuration that marks ProductCatalogInitializer as a Spring-managed bean and enables background initialization using BACKGROUND bootstrap mode:

@Configuration
public class AppConfig {

    @Bean(bootstrap = Bean.Bootstrap.BACKGROUND)
    public ProductCatalogInitializer productCatalogInitializer() {
        return new ProductCatalogInitializer();
    }
}

Spring detects the BACKGROUND bootstrap mode and offloads bean initialization to a container-managed bootstrapExecutor, allowing it to run on a separate thread instead of blocking the main application context refresh. Hence, this mechanism relies on a configured bootstrap executor. Without it, Spring can’t execute background initialization, and the affected beans fall back to normal synchronous initialization during startup.

5.2. Bean Injection

A background-initialized bean can be injected into other Spring-managed components in the same way as any standard singleton bean, since background initialization doesn’t change the core dependency injection model.

In most cases, direct injection remains sufficient because Spring coordinates the lifecycle and ensures that the bean becomes fully available within the application context startup phase. However, in scenarios where access may occur before the initialization process has completed, Spring provides ObjectProvider as an optional mechanism for deferred retrieval of the bean at runtime.
To that end, let’s create a service that demonstrates the injection of a background-initialized bean:

@Service
public class ProductService {

    private final ObjectProvider<ProductCatalogInitializer>
            initializerProvider;

    public ProductService(
            ObjectProvider<ProductCatalogInitializer> initializerProvider) {
                this.initializerProvider = initializerProvider;
    }

    public void printStatus() {

        ProductCatalogInitializer initializer = initializerProvider.getObject();

        System.out.println("Bean status: " + initializer.getStatus());
    }
}

Now, the dependency isn’t resolved during bean creation. Instead, Spring retains the reference and defers resolution until getObject() is invoked. At that point, the actual bean instance is retrieved, so access occurs only after background initialization has completed, while the injection phase remains independent of startup timing.

5.3. Application Startup Behavior with Background Initialization

With BACKGROUND bootstrap mode enabled, Spring offloads selected bean initialization to a background thread, allowing the application context refresh to proceed without waiting for these beans. As a result, startup becomes non-blocking for the selected initialization workload, while execution continues in parallel.

Despite this, non-lazy background-initialized beans remain part of the Spring container lifecycle, and their completion is coordinated within the overall startup process.

5.4. Performance Impact

This behavior directly reduces startup latency. Spring moves heavy bean initialization off the main refresh thread. As a result, the application becomes operational earlier while background tasks continue executing in parallel. Beans that load large caches, establish connection pools, or run schema validation benefit the most.

6. Conclusion

In this article, we explored background initialization in the Spring Framework using the BACKGROUND bootstrap mode, which enables selected beans to initialize asynchronously during application context refresh.

The mechanism decouples expensive bean initialization from the main startup thread while preserving the Spring lifecycle semantics. Rather than launching uncontrolled threads, Spring keeps full awareness of bean dependencies. If a non-lazy bean depends on one that is still initializing in the background, Spring ensures it waits, preventing access to incomplete or half-built objects. In addition, using ObjectProvider helps delay bean retrieval until it is actually needed, adding an extra layer of safety for early-access scenarios.

This approach improves application startup responsiveness in systems with heavy initialization workloads by enabling parallel execution during context refresh. It maintains dependency safety and lifecycle consistency while reducing blocking on the main thread. Background initialization is best suited for non-critical beans such as cache warmers, external integrations, and data preloading components.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW