How can I override Spring Boot application.properties programmatically?

后端 未结 10 1718
失恋的感觉
失恋的感觉 2020-11-29 18:33

I have jdbc property files which I take from external configuration web-service In spring boot in order to set mysql props it\'s easy as adding those to application.properti

10条回答
  •  时光说笑
    2020-11-29 18:58

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

    Something along the lines of:

    public class DatabasePropertiesListener implements ApplicationListener {
      public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        Properties props = new Properties();
        props.put("spring.datasource.url", "");
        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.

提交回复
热议问题