Skip to content

ApplicationContext parent-child hierarchy

The ApplicationContext parent-child hierarchy is a structural design in the Spring Framework allowing multiple ApplicationContext instances to be organized in a hierarchical relationship^[600-developer__java__spring__multipleApplicationContext.md]. This structure facilitates the definition of shared beans in a parent context while maintaining isolated beans in child contexts^[600-developer__java__spring__multipleApplicationContext.md].

Establishment

The hierarchy is established programmatically using the setParent(ApplicationContext parent) method available on the context instance^[600-developer__java__spring__multipleApplicationContext.md]. When a parent context is set, the environment configuration (specifically the ConfigurableEnvironment) of the parent is merged with that of the child context^[600-developer__java__spring__multipleApplicationContext.md].

The code typically follows a pattern where a parentCtx is defined, and subsequent childCtx instances are linked to it via childCtx.setParent(parentCtx) before refreshing the contexts^[600-developer__java__spring__multipleApplicationContext.md].

Visibility and Access

A key characteristic of this hierarchy is the unidirectional visibility of beans^[600-developer__java__spring__multipleApplicationContext.md].

  • Child Access: A child context can access and retrieve beans defined in its parent context (and recursively up the hierarchy to the root context)^[600-developer__java__spring__multipleApplicationContext.md].
  • Parent Isolation: A parent context cannot access beans defined in its child contexts^[600-developer__java__spring__multipleApplicationContext.md].

This allows a "Root Context" to serve as a shared infrastructure layer, while child contexts manage specific, isolated components^[600-developer__java__spring__multipleApplicationContext.md].

Lifecycle Management

The lifecycle of application contexts within the hierarchy is managed individually but is often tied to their creation sequence and dependency relationships^[600-developer__java__spring__multipleApplicationContext.md].

Contexts are initialized using the refresh() method^[600-developer__java__spring__multipleApplicationContext.md]. While they are distinct instances, closing a parent context does not necessarily immediately force child contexts to close if they are still being referenced by the application, although the parent's active status will change^[600-developer__java__spring__multipleApplicationContext.md].

For example, in a multi-level hierarchy, the destruction of a child context (via close()) sets its active status to false, but the parent context may remain active and accessible independently^[600-developer__java__spring__multipleApplicationContext.md].

  • [[applicationcontext|ApplicationContext]]
  • [[Bean Definition]]

Sources

^[600-developer__java__spring__multipleApplicationContext.md]