eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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 over on Github.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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 – LS – NPI – (cat=Spring)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments