How to extend already defined lists and maps in Spring application context?

后端 未结 2 1017
轻奢々
轻奢々 2021-02-02 14:45

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

2条回答
  •  生来不讨喜
    2021-02-02 15:33

    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.

提交回复
热议问题