Skip to content

Environment Merging in Spring Contexts

In the Spring Framework, the Environment abstraction encapsulates profiles and properties for an application context. When using hierarchical contexts (parent-child relationships), Spring automatically merges the parent's environment into the child's, ensuring that configuration settings propagate down the hierarchy^[600-developer__java__spring__multipleApplicationContext.md].

Mechanism

The merging process is initiated when a parent context is assigned to a child context via the setParent(ApplicationContext parent) method^[600-developer__java__spring__multipleApplicationContext.md].

The specific logic, as found in AnnotationConfigApplicationContext (and other ConfigurableApplicationContext implementations), checks if the parent context is non-null and if its environment is an instance of ConfigurableEnvironment^[600-developer__java__spring__multipleApplicationContext.md]. If both conditions are met, the container invokes the ConfigurableEnvironment.merge(ConfigurableEnvironment) method to combine the parent's environment into the child's environment^[600-developer__java__spring__multipleApplicationContext.md].

Behavior and Implications

This mechanism creates a unified configuration scope. Properties defined in a root or parent context become visible to descendant contexts, allowing shared configuration (such as feature flags or connection settings) to be defined once at a higher level and inherited automatically^[600-developer__java__spring__multipleApplicationContext.md].

The visibility of configuration and beans is strictly hierarchical. A child context has access to the merged environment and beans of its parents, but the reverse is not true: a parent context cannot access the environment or beans of its children^[600-developer__java__spring__multipleApplicationContext.md].

Usage Example

The following code demonstrates how to establish a parent-child relationship using AnnotationConfigApplicationContext. Calling childCtx.setParent(parentCtx) triggers the environment merge, allowing childCtx to inherit configuration from parentCtx^[600-developer__java__spring__multipleApplicationContext.md].

AnnotationConfigApplicationContext parentCtx = new AnnotationConfigApplicationContext();
parentCtx.setDisplayName("parentCtx");
AnnotationConfigApplicationContext childCtx = new AnnotationConfigApplicationContext();
childCtx.setDisplayName("childCtx");

// Configuration classes...
parentCtx.registerBean(Config01.class);
childCtx.registerBean(Config02.class);

// Establishing the relationship triggers the environment merge
childCtx.setParent(parentCtx); 

parentCtx.refresh();
childCtx.refresh();
  • [[Spring ApplicationContext]]
  • [[Bean Definition]]

Sources

^[600-developer__java__spring__multipleApplicationContext.md]