Quick revision
The short answer
A static ApplicationContextHolder turns the whole context into a hidden service locator: callers' real dependencies are invisible, tests need a full context, the static field points at only one context even when tests cache several, and any code that runs before the holder is set fails with a NullPointerException. We remove it step by step by giving callers their dependencies through constructors, moving logic out of entities or using domain events, blocking new uses with a build rule, and deleting the holder once tests show nothing still needs it.
What to remember
In this answer, we saw that a static ApplicationContextHolder is a hidden service locator. It hides dependencies and forces full contexts in tests, it breaks when the test framework caches several contexts in one JVM because one static field can point at only one of them, and it fails for code that runs before Spring sets it. We removed it caller by caller: constructor injection for beans, beans or parameters for utilities, services or domain events for entities, with characterisation tests and a build rule that stops new uses until the holder can be deleted.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A static ApplicationContextHolder turns the whole context into a hidden service locator: callers' real dependencies are invisible, tests need a full context, the static field points at only one context even when tests cache several, and any code that runs before the holder is set fails with a NullPointerException. We remove it step by step by giving callers their dependencies through constructors, moving logic out of entities or using domain events, blocking new uses with a build rule, and deleting the holder once tests show nothing still needs it.
Why this question is asked
Many Spring codebases contain a class like ApplicationContextHolder or SpringContext with a static getBean() method. It usually appeared because someone needed a bean in a place Spring does not create, such as a JPA entity or a static utility, and it spread because it was convenient. Interviewers ask about it because removing it well needs an understanding of how Spring manages objects, how the test framework caches contexts, and how to refactor a large codebase without breaking it. In this answer, we will look at how the holder works, go through the problems it causes one by one, and then plan its removal.
1How the Holder Works
The pattern is short. A bean implements ApplicationContextAware, Spring calls setApplicationContext() during startup, and the bean stores the context in a static field. Any code anywhere in the JVM can then call a static method to fetch a bean.
Notice that nothing in the signature of Order or totalWithTax() tells us it needs a TaxService. The only way to find out is to read the method body, or to run it without a context and watch it fail.
2Problem 1: A Hidden Service Locator
A service locator is an object that code asks for its dependencies at runtime, instead of receiving them. Dependency injection exists to avoid exactly this. With the holder, the container cannot check at startup that a caller's dependencies exist, a reader cannot see them, and a unit test of Order cannot simply pass a fake TaxService. To test totalWithTax(), we must start a Spring context that contains a TaxService and everything it needs, which turns a millisecond unit test into a slow integration test.
It also hides the direction of dependencies. An entity in the domain layer is now calling a service layer bean, so layering rules are broken without anything showing up in imports except one innocent-looking utility.
3Problem 2: More Than One Context in the JVM
The static field can hold only one context. That sounds fine in production, where there is usually one, but the Spring TestContext framework caches application contexts and keeps several alive in the same JVM: one for each distinct test configuration. Each time a new context starts, its holder bean overwrites the static field. A later test that reuses an earlier cached context then calls the holder and gets beans from the wrong context, perhaps one with different mocks or a different database.
The failures look random: a test passes alone and fails in the full suite, or depends on which test class ran just before. The same problem appears with parent and child contexts, or with several Spring applications running in one server.
7 messages in order. Play them, or step through them one at a time.
Whichever context started last wins, regardless of which one the test is using.
4Problem 3: Code That Runs Before the Holder Is Set
The static field is empty until Spring creates the holder bean and calls its setter. Code that runs earlier, such as a static initialiser, another bean's constructor that happens to be created before the holder, a Hibernate type loaded during the EntityManagerFactory setup, or a batch tool that runs without Spring, gets a NullPointerException from context.getBean(). Teams then add @DependsOn or @Order hacks to force the holder to be created first, which makes the startup order fragile. After the context closes, the field still points at a closed context, so late calls during shutdown fail too.
5Removing It Step by Step
We start by listing every caller. A search for the holder's class name gives the list, and grouping the callers shows three kinds. Spring beans that use the holder out of habit are the easiest: we add the dependency to their constructor and delete the call. Utilities with static methods become small beans, or their static methods take the dependency as a parameter. Entities are the interesting case, because Hibernate creates them, not Spring.
For entities, the cleanest fix is to move the behaviour that needs a service out of the entity: an application service loads the order, calls the tax service and stores the result. When the entity really must announce something, such as an order being placed, we use domain events instead of calling services: the entity records an event and Spring Data publishes it when the repository saves the aggregate. Listeners, which are ordinary beans with injected dependencies, do the work.
- List all callers and group thembeans, utilities, entities
- Block new uses with a build ruleallow-list only shrinks
- Beans: constructor injectionadd test, remove
getBean - Utilities: make them beans or pass parameters
- Entities: move logic to services or use domain events
- Allow-list empty?YesDelete the holderNoNext caller
6 steps in order. Play them, or step through them one at a time.
Each caller is a small, separately tested change.
To keep the work safe, we add characterisation tests around each caller before changing it, so we know the behaviour is the same afterwards. We mark the holder @Deprecated and add an ArchUnit rule or a similar build check that forbids new uses, with a list of allowed existing callers that only shrinks. When the list is empty, we delete the holder, and the test suite usually gets faster because many tests no longer need a full context.
6Follow-up questions
Is it ever acceptable to keep a static context holder?
Rarely, and only at a boundary Spring cannot reach, such as a legacy library that instantiates our classes by reflection and offers no factory hook. Even then, it is better to keep the holder in one adapter class at that boundary and pass the looked-up beans inward, so the rest of the code stays clean. Many libraries, including Hibernate and Quartz integration, now allow Spring to supply instances, which removes the need.
Why not use @Configurable with AspectJ to inject into entities?
@Configurable with AspectJ weaving can inject beans into objects created with new, including entities. It works, but it needs load-time or compile-time weaving, adds magic to every constructor call, and still puts service dependencies inside domain objects. Moving the behaviour into services or using domain events keeps entities simple and testable without any weaving.
How do domain events in Spring Data work?
An aggregate either extends AbstractAggregateRoot and calls registerEvent(), or exposes a method annotated with @DomainEvents. When we call save() on its Spring Data repository, Spring Data publishes those events through the application event publisher and then clears them. Listeners annotated with @EventListener or @TransactionalEventListener receive them; the transactional variant can run only after the transaction commits, which is often what we want for side effects.
7Conclusion
In this answer, we saw that a static ApplicationContextHolder is a hidden service locator. It hides dependencies and forces full contexts in tests, it breaks when the test framework caches several contexts in one JVM because one static field can point at only one of them, and it fails for code that runs before Spring sets it. We removed it caller by caller: constructor injection for beans, beans or parameters for utilities, services or domain events for entities, with characterisation tests and a build rule that stops new uses until the holder can be deleted.
Open with
The holder is a static service locator, and it causes three kinds of trouble. First, dependencies are hidden: an entity calling getBean for a TaxService has no sign of that in its signature, the container cannot check it at startup, and any test of that code needs a full Spring context.
Then, if they want more
Second, it assumes one context per JVM. The Spring test framework caches several contexts, and each new one overwrites the static field, so a test using an older cached context may get beans, including mocks, from a different one. That gives flaky, order-dependent tests.
Third, anything that runs before the holder bean is initialised, or after the context closes, fails with a null pointer or a closed context. To remove it, I would list all callers and group them. Spring beans get the dependency through the constructor. Static utilities become beans or take parameters.
For entities I would move the logic that needs services into an application service, or use Spring Data domain events so listeners do the work. I would add tests before each change, deprecate the holder, add an ArchUnit rule against new uses with a shrinking allow-list, and delete it when the list is empty.
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.
- Official documentation
- Spring Framework reference, Core technologies
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 codebase has a static ApplicationContextHolder set through ApplicationContextAware...": https://scrivio-interview-library.netlify.app/spring-boot/bean-lifecycle/650593208c/