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;
}
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);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.