How can I override Spring Boot application.properties programmatically?

You can add additional property sources in a lifecycle listener reacting to ApplicationEnvironmentPrepared event.

Something along the lines of:

public class DatabasePropertiesListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
  public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    Properties props = new Properties();
    props.put("spring.datasource.url", "<my value>");
    environment.getPropertySources().addFirst(new PropertiesPropertySource("myProps", props));
  }
}

Then register the class in src/main/resources/META-INF/spring.factories:

org.springframework.context.ApplicationListener=my.package.DatabasePropertiesListener

This worked for me, however, you are sort of limited as to what you can do at this point as it’s fairly early in the application startup phase, you’d have to find a way to get the values you need without relying on other spring beans etc.

Leave a Comment