我需要将 Spring Boot 应用程序的配置保存在数据库中。
是否可以将数据库信息存储在 application.properties
并使用它们连接到数据库并从那里检索所有其他属性?
所以我的 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();
}
}
与 ApplicationConfiguration
作为 Entity
。
但是 Spring Boot 并没有从数据库中获取配置。
原文由 deve 发布,翻译遵循 CC BY-SA 4.0 许可协议
我知道这是一个老问题,但我在寻找解决方案时偶然发现了它,并想分享一种对我有用的方法。
一种方法是使用 org.springframework.boot.env.EnvironmentPostProcessor 的实现。下面是我使用的一个实现,它对我来说效果很好。您必须使用以下条目将 META-INF/spring.factories 文件添加到您的部署中:
您可以从此处的文档中阅读更多相关信息: https ://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-boot-application.html#howto-customize-the-environment - 或应用程序上下文