addOrMerge method
Adds a new MapPropertySource with the given name, or merges the provided
source map into an existing one if a property source with the same name
is already present.
This method is designed for dynamic, incremental configuration updates, such as loading layered configuration files, merging environment overrides, or applying runtime-provided settings.
Behavior
-
If no property source with the given
nameexists:- A new MapPropertySource is created containing all key–value pairs
from
source. - It is added with lowest precedence using addLast.
- A new MapPropertySource is created containing all key–value pairs
from
-
If a matching property source does exist:
- The existing source is retrieved and merged (when possible) by mergeIfPossible.
- The merged result becomes a new MapPropertySource.
- It replaces the old source using replace.
If source is empty, this method performs no action.
Example
sources.addOrMerge({'debug': 'true'}, 'env');
// If 'env' already exists, keys are merged.
// If not, a new MapPropertySource('env') is added.
Implementation
void addOrMerge(Map<String, Object> source, String name) {
if (source.isNotEmpty) {
final resultingSource = <String, Object>{};
final propertySource = MapPropertySource(name, resultingSource);
if (containsName(name)) {
mergeIfPossible(source, resultingSource, name);
replace(name, propertySource);
} else {
resultingSource.addAll(source);
addLast(propertySource);
}
}
}