Interview Prep Zoneby CuriouserLabs

Question 5 of 5 · architect level

ApplicationContext vs BeanFactory, and when do context hierarchies or multiple contexts make sense?

🎤 Say this first

BeanFactory is the bare container: definitions, wiring, lazy getBean. ApplicationContext extends it with eager singleton pre-instantiation, automatic post-processor detection, events, i18n, resources and environment abstraction — always use the context; the raw factory is for framework-embedding niches. Hierarchies (parent/child) let children see parent beans but not vice versa: historically web MVC (root services ↔ dispatcher web beans), today mostly relevant for plugin systems, embedding, and Spring Cloud's bootstrap context.

The full picture

  • What the context adds concretely: BPP/BFPP auto-registration (BeanFactory requires manual wiring of them!), MessageSource, ApplicationEventPublisher, Environment/profiles, resource loading (classpath:), and startup-time failure of misconfigured singletons.
  • Hierarchy semantics: child looks up parent for missing beans; component scan does not cross upward; events don't propagate down; each child can override parent definitions locally.
  • Where you still meet it: classic ContextLoaderListener root + DispatcherServlet child; Spring Cloud Config's bootstrap parent; test slices building trimmed contexts; frameworks like Spring Batch creating step-scoped child-ish contexts.
  • Multiple independent contexts in one JVM: plugin isolation (each plugin its own context + classloader), embedding Spring in a larger app, or module-per-context modular monolith experiments (Spring Modulith took the lighter path instead).

🔄 Likely follow-up questions

  • Why must BeanPostProcessors be registered manually with a raw BeanFactory?
  • How does Boot's single-context model differ from classic root+servlet contexts?
  • How does the Spring TestContext framework cache contexts, and what invalidates the cache?