Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A bean's constructor calls a method on an injected dependency that has not finished its own initialisation, causing a NullPointerException at startup. How do you diagnose and fix initialisation order problems?

A constructor-injected dependency is always fully initialised before it is passed in, unless it is a @Lazy proxy or part of a cycle, so this NPE usually comes from field injection read in the constructor, from static access to beans, or from an early reference handed out during a cycle. We diagnose it by reading which reference is null and by looking at the creation order in debug logs or the startup actuator endpoint, and we fix it with constructor injection, @DependsOn for beans without a direct reference, or by moving cross-bean work to SmartInitializingSingleton or ApplicationReadyEvent.

Why this question is asked

Initialisation order bugs are frustrating because they often appear only after an unrelated change: a new bean, a renamed class, a different classpath order, and suddenly startup fails with a NullPointerException deep in a constructor. Interviewers ask this to see whether we can reason from the lifecycle to the cause, rather than shuffling annotations until it works. In this answer, we will recap what Spring guarantees about order, go through the three usual causes with code, see how to observe the real creation order, and then look at the fixes, including @DependsOn and running work after the context is ready.

1What Spring Guarantees About Order

Spring creates a singleton by first resolving everything its constructor needs. If OrderService takes a PricingService in its constructor, Spring creates PricingService first and runs its whole lifecycle: constructor, field injection, @PostConstruct, init methods and post-processors. Only then does it call the OrderService constructor. So a constructor-injected dependency is a finished bean, and calling it from our constructor is safe.

There are two exceptions. A parameter marked @Lazy receives a proxy that creates the real bean on first call, so any problem appears in that call. And when beans form a cycle, one of them may receive an early reference to a bean that is not finished yet. Outside of these, Spring makes no promise about the order of beans that do not reference each other: two unrelated singletons may be created in either order, and that order can change when the code changes.

2Cause 1: Field Injection Read in the Constructor

The most common cause is not a dependency that is unfinished, but one that has not been injected yet.

Java
@Service
class OrderService {
@Autowired private PricingService pricing; // field injection
private final BigDecimal minimum;
OrderService() {
this.minimum = pricing.minimumOrder(); // NullPointerException: pricing is null
}
}

Spring fills @Autowired fields after the constructor returns, because it can only set fields on an object that exists. So inside the constructor the field is always null, no matter how finished PricingService is. The stack trace points at our constructor, and the message from the helpful NullPointerException feature of the JDK says exactly which reference was null: Cannot invoke PricingService.minimumOrder() because this.pricing is null. The fix is constructor injection, which also makes the dependency final and the class easier to test.

3Cause 2: Static Access to Beans

The second cause is a static shortcut. Some codebases have a holder class that stores the application context or a bean in a static field so that non-Spring code can reach it.

Java
@Component
class SpringContext implements ApplicationContextAware {
static ApplicationContext ctx;
public void setApplicationContext(ApplicationContext c) { ctx = c; }
}
@Component
class AuditTrail {
private final Clock clock;
AuditTrail() {
this.clock = SpringContext.ctx.getBean(Clock.class); // NPE if SpringContext was not created yet
}
}

Spring does not know that AuditTrail needs SpringContext, because there is no injection, only a static read. So the order is whatever the bean factory happens to choose, and the code works until a refactoring changes it. The fix is to inject Clock directly. Static holders should be a last resort for code Spring does not create, and never be used during startup.

4Cause 3: Early References in a Cycle

The third cause appears in applications that allow circular references. If A and B inject each other through fields, Spring creates A, hands an early reference of the half-built A to B, and only then finishes A. If B's @PostConstruct calls a method on A that uses one of A's fields, that field may still be null, because A has not been populated yet. The NPE then looks random, since it depends on which of the two Spring creates first.

This is one reason Spring Boot forbids circular references by default since 2.6. If an application sets spring.main.allow-circular-references=true and has this kind of NPE, removing the cycle is the real fix.

5Seeing the Real Creation Order

Guessing is slow, so we look. Two tools show the order in which Spring created beans. The first is debug logging of the bean factory, which prints a line each time a singleton is created. The second is the startup endpoint of Spring Boot Actuator, which records startup steps with their bean names and durations when the application uses a BufferingApplicationStartup.

Java
# application.properties
logging.level.org.springframework.beans.factory.support.DefaultListableBeanFactory=DEBUG
# log, in creation order
DEBUG ... Creating shared instance of singleton bean 'auditTrail'
DEBUG ... Creating shared instance of singleton bean 'springContext' <- created after auditTrail
DEBUG ... Creating shared instance of singleton bean 'orderService'
// main(): app.setApplicationStartup(new BufferingApplicationStartup(4096));
// GET /actuator/startup -> steps named spring.beans.instantiate, each tagged with beanName
Step throughDiagnosing a startup NullPointerException
  1. Read the helpful NPE messagewhich reference was null
  2. Is it an @Autowired field used in a constructor?
    YesSwitch to constructor injectionNoLook at how the reference was obtained
  3. Is it a static holder or lookup?
    YesInject the bean directlyNoCheck for a cycle or @Lazy proxy
  4. Check creation orderdebug log or /actuator/startup
  5. Use @DependsOn or move work after the context is ready

5 steps in order. Play them, or step through them one at a time.

Notice that the log shows auditTrail created before springContext, which explains cause 2 at once. The startup endpoint gives the same order with timings and the nesting of beans created for other beans, which is useful for cause 3.

6Fixes: @DependsOn and Work After the Context Is Ready

Sometimes one bean must be created before another without any reference between them. A schema migrator is the classic case: the code that migrates the database must run before any bean that queries it, but the repositories never call the migrator. @DependsOn tells Spring about this hidden order. Spring Boot's Flyway and Liquibase support already sets up such a dependency for the JPA EntityManagerFactory, so we usually need it only for our own components.

Java
@Component
class SchemaMigrator {
@PostConstruct void migrate() { /* apply SQL scripts */ }
}
@Component
@DependsOn("schemaMigrator") // created only after schemaMigrator is fully initialised
class ReferenceDataLoader { /* reads tables the migrator creates */ }
@Component
class RouteTableBuilder implements SmartInitializingSingleton {
@Override public void afterSingletonsInstantiated() {
// runs once every non-lazy singleton exists: safe to look at all of them
}
}

The better fix for most cross-bean work is to stop doing it during creation. SmartInitializingSingleton.afterSingletonsInstantiated() runs once all non-lazy singletons exist, which suits work that combines several beans. ApplicationReadyEvent runs when Spring Boot has fully started, including the web server, which suits warm-ups and data loads. Both remove the order question entirely, because by then every bean is finished.

7Follow-up questions

Why not add @DependsOn everywhere to be safe?

Because it hides real dependencies and makes the order hard to understand. If a bean uses another, it should inject it, and Spring will order them correctly. @DependsOn is for side-effect relationships only, such as a migrator or a component that registers something globally.

Can @Order or Ordered control creation order?

No. @Order affects the order of beans in an injected list and of some callbacks, such as filters or listeners, but not the order in which singletons are created. Creation order follows dependencies, @DependsOn and, for unrelated beans, the registration order, which we should not rely on.

Why does the order change after an unrelated change?

For beans without a dependency between them, Spring creates them roughly in registration order, which depends on component scanning, class names and configuration order. Adding or renaming a class can change it, which is exactly why code that depends on that accidental order breaks.

8Conclusion

In this answer, we saw that Spring guarantees a constructor-injected dependency is fully initialised, except for @Lazy proxies and cycles. Startup NPEs therefore usually come from field injection read in the constructor, from static access to beans that Spring cannot see, or from early references in a cycle. We found the real creation order with debug logging and the startup actuator endpoint, and we fixed the problems with constructor injection, @DependsOn for side-effect dependencies such as a schema migrator, and by moving cross-bean work to SmartInitializingSingleton or ApplicationReadyEvent.

What to say in the interviewAbout 80 seconds aloud

Open with

I start from what Spring guarantees: if a bean takes a dependency in its constructor, Spring creates that dependency first and runs its whole lifecycle, so it is finished when my constructor runs, unless it is a @Lazy proxy or part of a cycle.

Then, if they want more

So when I see an NPE in a constructor, I look for the cases outside that guarantee. The most common is field injection: the constructor reads an @Autowired field, but fields are only injected after the constructor returns, so it is always null, and the helpful NPE message even names this.pricing.

The second is static access, like a static ApplicationContext holder, because Spring cannot see that dependency and creates the beans in whatever order it likes. The third is an early reference in a circular dependency, where one bean sees the other half-built.

To confirm, I turn on debug logging for DefaultListableBeanFactory, which logs each singleton as it is created, or use the actuator startup endpoint with BufferingApplicationStartup.

Then I fix it: constructor injection, injecting the bean instead of a static lookup, @DependsOn when there is a real side-effect order like a schema migrator, and for work that needs several beans, I move it to SmartInitializingSingleton or ApplicationReadyEvent, when everything is ready.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A bean's constructor calls a method on an injected dependency that has not finished its...": https://scrivio-interview-library.netlify.app/spring-boot/bean-lifecycle/425c3a2553/