我需要将 Spring Boot 应用程序的配置保存在数据库中。
是否可以将数据库信息存储在application.properties
并使用它们连接到数据库并从那里检索所有其他属性?
So my application.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
其他配置将从数据库中获取,如下所示:
@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();
}
}
With ApplicationConfiguration
as an Entity
.
但是 Spring Boot 不会从数据库获取配置。
您可以锻炼的一种可能的解决方案是使用可配置环境并重新加载并添加属性。
@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));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)