Multi-level context hierarchy¶
Multi-level context hierarchy refers to the architectural pattern within the Spring Framework where multiple ApplicationContext instances are organized in a parent-child tree structure^[600-developer__java__spring__multipleApplicationContext.md].
In this hierarchy, a child context is linked to a parent context via the setParent(ApplicationContext parent) method^[600-developer__java__spring__multipleApplicationContext.md]. This configuration allows for a layered application architecture, commonly used to separate business logic from infrastructure concerns (e.g., separating a root web context from child servlet contexts).
Core Mechanism¶
When a parent context is established, the child context can access beans defined in the parent, but the parent context cannot access beans defined in the child^[600-developer__java__spring__multipleApplicationContext.md]. This unidirectional visibility allows child contexts to depend on shared services defined in the root, while maintaining isolation for their specific components.
Additionally, if the parent context is non-null and its environment is an instance of ConfigurableEnvironment, the parent's environment is automatically merged into the child context's environment^[600-developer__java__spring__multipleApplicationContext.md].
Lifecycle and Refresh¶
The initialization of a multi-level hierarchy follows a specific sequence to ensure availability of dependencies. The refresh() operation must typically be called on the parent context before it is called on the child context^[600-developer__java__spring__multipleApplicationContext.md].
This order ensures that the singleton beans and infrastructure in the parent are fully initialized before the child context attempts to retrieve them.
Implementation Example¶
In the Spring Framework, this structure is implemented using the AnnotationConfigApplicationContext class^[600-developer__java__spring__multipleApplicationContext.md].
- Instantiation: Multiple context objects are created (e.g.,
parentCtx,childCtx). - Linking: The hierarchy is defined using
childCtx.setParent(parentCtx). - Bean Registration: Specific configuration classes or beans are registered to each context (e.g.,
parentCtx.registerBean(Config01.class)). - Activation: The
refresh()method is invoked starting from the root parent down to the deepest child^[600-developer__java__spring__multipleApplicationContext.md].
For example, a Car bean in the root context is accessible to a childCtx2, but a Dog bean in childCtx is not accessible to the parentCtx^[600-developer__java__spring__multipleApplicationContext.md].
Related Concepts¶
- Spring Framework
- [[Dependency Injection]]
- [[Scope]]
Sources¶
^[600-developer__java__spring__multipleApplicationContext.md]