0

I want to load properties file that is outside the springboot app and override the sprignboot matched application properties on the run time environment Programmatically not through server context/ runtime args?

I have found a way to implement this by creating listener for ApplicationEnvironmentPreparedEvent. working code example link: https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.core.env.ConfigurableEnvironment

But looking for much more easy and spring boot managed solution

something like this (below code is not working though) :

SpringApplication application = new SpringApplication(MainApplication.class);
application.setBannerMode(Mode.OFF);
Properties props = new Properties();
try{
 props.load(newFileInputStream(
   "C:\\...\\PropFile\\applicationconfig.properties"));
application.setDefaultProperties(props);
application.run(args);
} catch (Exception e) {
//print exception here;
}
Bitla
  • 71
  • 1
  • 5
  • you can take a look this tutorial baeldung.com/spring-reloading-properties – Jonathan JOhx Nov 06 '19 at 19:43
  • `"C:\\...\\PropFile\\applicationconfig.properties"));`. Don't you think this path is wrong? there is nothing as such `...`. – ialam Nov 06 '19 at 19:49
  • @Jonathan, i will try and let you know (One thing i saw in tutorial is we have to pass the file path as an CL argument. In my case i do not have that option). – Bitla Nov 10 '19 at 12:33
  • @ialam, im just giving an example of the path. i know "..." is not correct. – Bitla Nov 10 '19 at 12:34

1 Answers1

0

You can achieve same using spring EnvironmentPostProcessor.

public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {
    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Resource path = new ClassPathResource("com/example/myapp/config.yml");
        PropertySource<?> propertySource = loadYaml(path);
        environment.getPropertySources().addLast(propertySource);
    }
    private PropertySource<?> loadYaml(Resource path) {
        if (!path.exists()) {
            throw new IllegalArgumentException("Resource " + path + " does not exist");
        }
        try {
            return this.loader.load("custom-resource", path, null);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
        }
    }
}

spring doc

Abhinav manthri
  • 151
  • 1
  • 14