Load Yml at runtime with Spring Boot

1.5k views Asked by At

I have multiple yml files in different folders. All the files in the folder share the same property structure which I mapped with a java bean.

At runtime, with a factory, I want to get the right bean populated with the values of the specific file chosen at runtime. How do I do that?

Thanks

2

There are 2 answers

2
Alejandro Alanis On BEST ANSWER

The @ConfigurationProperties annotation or the mechanism behind it is built to be used for configuration of an application at startup, not loading data at runtime.

I'm sure you could somehow start mini spring environments at runtime just to read this data using different spring profiles (this is e.g. how spring-cloud-configserver loads properties) but this seems not right and there are better alternatives.

E.g., if you need that data to be loaded at runtime, you can use jackson's yamlfactory for that, with that you can read your data in 3-4 statements. A good example is here: https://www.baeldung.com/jackson-yaml.

0
Pam Stums On

Consider a Bean like this: (Pseudo code, just to explain)

class MyConfigBean {
   private Properties currentProperties;
   private Map<String, Properties> allPropertiesMap;

   void loadAllProperties() { ... }

   void switchProperties(String name) {
       this.currentProperties = this.allPropertiesMap.get(name);
   }

   String getProperty(String key) {
     return this.currentProperties.get(key);
   }
}

You can load all of the Yaml files into a Map in your bean. The Map's key could be the "name" of the properties file and the value would be the Properties object. A switchProperties(String name) method will "select" the properties file you wish to work with. Using the name, you will get the appropriate Properties object from the Map and assign it to the "currentProperties" object.

This way, each time you get a property by key, it will be fetched from the "currentProperties" according to what you "switched" for.
Important - You'll have to decide what is the default properties after you load all of them.