Spring Boot: Use database and application.properties for configuration

后端 未结 7 1523
无人及你
无人及你 2020-12-29 15:52

I need to save the configuration of the Spring Boot application in the database.

Is it possible to store the database information in the application.properties

7条回答
  •  不思量自难忘°
    2020-12-29 16:22

    I unfortunately don't have a solution for this problem yet, but I use the following workaround for now (requires an additional application restart on configuration change).

    @Component
    public class ApplicationConfiguration {
    
        @Autowired
        private ConfigurationRepository configurationRepository;
    
        @Autowired
        private ResourceLoader resourceLoader;
    
        @PostConstruct
        protected void initialize() {
            updateConfiguration();
        }
    
        private void updateConfiguration() {
            Properties properties = new Properties();
    
            List configurations = configurationRepository.findAll();
            configurations.forEach((configuration) -> {
                properties.setProperty(configuration.getKey(), configuration.getValue());
            });
    
            Resource propertiesResource = resourceLoader.getResource("classpath:configuration.properties");
            try (OutputStream out = new BufferedOutputStream(new FileOutputStream(propertiesResource.getFile()))) {
                properties.store(out, null);
            } catch (IOException | ClassCastException | NullPointerException ex) {
                // Handle error
            }
        }
    
    }
    

    I load the configuration from the database and write it to an another property file. This file can be used with @PropertySource("classpath:configuration.properties").

提交回复
热议问题