Spring Boot:使用database和application.properties进行配置 [英] Spring Boot: Use database and application.properties for configuration

查看:396
本文介绍了Spring Boot:使用database和application.properties进行配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在数据库中保存Spring Boot应用程序的配置。

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

是否可以将数据库信息存储在应用程序中.properties 并使用它们连接到数据库并从那里检索所有其他属性?

Is it possible to store the database information in the application.properties and use them to connect to the database and retrieve all the other properties from there?

所以我的应用程序.properties 看起来像:

spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=mydb
spring.datasource.username=user
spring.datasource.password=123456
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect

其他配置将从数据库中获取,如下所示:

And the other configuration would be fetched from the database with something like this:

@Configuration
@PropertySource(value = {"classpath:application.properties"})
public class ConfigurationPropertySource {

    private final ConfigurationRepository configurationRepository;

    @Autowired
    public ConfigurationPropertySource(ConfigurationRepository configurationRepository) {
        this.configurationRepository = configurationRepository;
    }

    public String getValue(String key) {
        ApplicationConfiguration configuration = configurationRepository.findOne(key);
        return configuration.getValue();
    }

}

ApplicationConfiguration 作为实体

但Spring Boot无法从中获取配置数据库。

But Spring Boot does not get the configuration from the database.

推荐答案

您可以使用 ConfigurableEnvironment 并重新加载和添加属性。

One possible solution that you could workout, is to use ConfigurableEnvironment and reload and add properties.

@Configuration   
public class ConfigurationPropertySource {

private ConfigurableEnvironment env;

private final ConfigurationRepository configurationRepository;

    @Autowired
    public ConfigurationPropertySource(ConfigurationRepository configurationRepository) {
        this.configurationRepository = configurationRepository;
    }

    @Autowired
    public void setConfigurableEnvironment(ConfigurableEnvironment env) {

        this.env = env;
   }

   @PostConstruct
   public void init() {
    MutablePropertySources propertySources = env.getPropertySources();
       Map myMap = new HashMap();
       //from configurationRepository get values and fill mapp
       propertySources.addFirst(new MapPropertySource("MY_MAP", myMap));
   }

}

这篇关于Spring Boot:使用database和application.properties进行配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆