Imagine a staged application context with different phases. We start with an early phase to define the necessary infrastructure. The xml application contexts are loaded sequenti
You can define exampleMapping
is the second definition is in a separate file, and you use
to import one file into another, but it's a fragile approach, and easily broken.
I suggest a more robust strategy. Replace the exampleMapping
with a Registry
class, which in turn contains and manages the mappings:
public MappingRegistry {
private final Map mappings = new HashMap();
public void addMapping(K key, V value) {
mappings.put(key, value);
}
public Map getMappings() {
return Collections.unmodifiableMap(mappings);
}
}
Then, write a class which registers a mapping with the registry:
public class MappingRegistrar {
private final MappingRegistry registry;
private K key;
private V value;
@Autowired
public MappingRegistrar(MappingRegistry registry) {
this.registry = registry;
}
public void setKey(K key) {
this.key = key;
}
public void setValue(V value) {
this.value = value;
}
@PostConstruct
public void registerMapping() {
registry.addMapping(key, value);
}
}
The your config becomes something like this:
These mappings can now be scattered throughout your config in any way you see fit, and they will self-assemble. ExampleServcie
is then injected with the MappingRegistry
and extracts the mappings accordingly.
It's a bit more work than what you already have, but it's a lot more flexible and less error prone. This is particularly valuable if you're trying to build an extensible framework of some kind; you want to put fewer constraints on how people use it.