Skip to content

Dynamic context addition and refresh

Dynamic context addition and refresh refers to the capability within the Spring Framework to modify application context hierarchies at runtime. This involves adding new child contexts to an existing parent context and invoking the refresh() lifecycle method to initialize these new components while the application continues to run^[600-developer__java__spring__multipleApplicationContext.md].

This feature allows for the modular extension of an application's runtime environment without requiring a full system restart.

Core Concepts

The implementation relies on the AnnotationConfigApplicationContext class and its parent-child hierarchy mechanisms^[600-developer__java__spring__multipleApplicationContext.md].

  • Parent Context (Root): The base context, often referred to as the ROOT CTX, which contains shared beans or configurations^[600-developer__java__spring__multipleApplicationContext.md].
  • Child Context: A newly created context registered with a parent. Child contexts can see and access beans defined in the parent contexts^[600-developer__java__spring__multipleApplicationContext.md].
  • Visibility and Isolation: A key property of this hierarchy is that visibility is unidirectional; a child context can access beans from the parent (e.g., childCtx2.getBean(Car.class)), but a parent context cannot access beans defined in its children^[600-developer__java__spring__multipleApplicationContext.md].
  • Lifecycle Management: The refresh() method is crucial. It processes the registered beans and initializes the specific context. Closing a child context (close()) stops it without necessarily terminating the parent or other active contexts^[600-developer__java__spring__multipleApplicationContext.md].

Implementation Workflow

A typical workflow for dynamically adding and refreshing a context involves the following steps^[600-developer__java__spring__multipleApplicationContext.md]:

  1. Establish Parent: Initialize the root context (e.g., parentCtx) and register its configuration classes. Ensure refresh() is called on the parent to activate it.
  2. Create Child: Instantiate a new AnnotationConfigApplicationContext.
  3. Register Configuration: Define the specific beans for this new context using registerBean(Class).
  4. Set Hierarchy: Use childCtx.setParent(parentCtx) to link the new context to the existing hierarchy.
  5. Refresh Child: Call refresh() on the child context to initialize its beans.

Sources

  • 600-developer__java__spring__multipleApplicationContext.md