How I Tripped on Spring DI Lifecycle

Debalina DharDebalina Dhar
1 min read

Table of contents

## The Problem

I had a class `RegionContextBuilder` that extended a base class `ContextBuilderBase`.

In the constructor of `ContextBuilderBase`, it called `buildContext()`.

This method required a Spring-injected bean `CountryFilterRepository`,

which is another subclass of `ContextBuilderBase`.

But — surprise — `CountryFilterRepository` wasn’t injected yet.

Spring threw a null pointer at me like it meant war.

---

## Why It Happened

I was trying to use a Spring-injected bean **inside the constructor** of a class.

But Spring injects dependencies **after** the constructor runs.

So my bean was basically unavailable during that time. Totally valid — just not obvious when you're deep in the weeds.

---

## The Fix

I moved `buildContext()` out of the constructor and into a method marked with:

```java

@PostConstruct

public void init() {

buildContext();

}

This ensures that buildContext() runs after all dependencies are injected. Clean and lifecycle-safe.

---

What I Learned

Spring’s DI lifecycle matters more than I thought.

Avoid doing too much in constructors — especially anything that relies on injected beans.

@PostConstruct is your friend when you need setup after injection.

---

Bonus Realization

I spent way too long thinking I was just bad at Spring.

Turns out, it’s just one of those “you only know once you get burned” lessons.

0
Subscribe to my newsletter

Read articles from Debalina Dhar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Debalina Dhar
Debalina Dhar