Skip to content

Spring ApplicationContext Hierarchy

The Spring ApplicationContext Hierarchy refers to the ability to create a tree-like structure of application contexts where a child context is linked to a parent context.^[600-developer__java__spring__multipleApplicationContext.md]

This relationship is established using the setParent(ApplicationContext parent) method available on the ConfigurableApplicationContext interface.^[600-developer__java__spring__multipleApplicationContext.md]

Environment Merging

When a parent context is set, the Spring container automatically manages the configuration environments of both contexts. If the parent context is non-null and its environment is an instance of ConfigurableEnvironment, the child context's environment will merge with the parent's environment.^[600-developer__java__spring__multipleApplicationContext.md]

This ensures that configuration properties and profiles defined in the parent are accessible within the child context.^[600-developer__java__spring__multipleApplicationContext.md]

Bean Visibility

A core characteristic of the context hierarchy is the unidirectional visibility of beans.

  • Child to Parent Visibility: A child context can access and retrieve beans defined in its ancestor contexts.^[600-developer__java__spring__multipleApplicationContext.md]
  • Parent Isolation: Conversely, a parent context cannot access beans defined in its child contexts.^[600-developer__java__spring__multipleApplicationContext.md]

This structure allows for a modular design where common infrastructure beans (such as data sources or shared services) might reside in a root context, while specific application beans reside in child contexts.^[600-developer__java__spring__multipleApplicationContext.md]

Lifecycle and Management

Each context in the hierarchy manages its own lifecycle independently.^[600-developer__java__spring__multipleApplicationContext.md]

To initialize the contexts, the refresh() method must be called on each specific instance^[600-developer__java__spring__multipleApplicationContext.md].

Closing a context (e.g., via close()) triggers the destruction of beans within that specific context and sets its active status to false, but it does not automatically close or destroy its parent context^[600-developer__java__spring__multipleApplicationContext.md]. The parent context may remain active and continue to serve other child contexts.

Sources

^[600-developer__java__spring__multipleApplicationContext.md]