gpt4 book ai didi

java - Spring 启动 : switch between embedded and postgresql datasources by changing a flag

转载 作者:行者123 更新时间:2023-11-29 04:06:17 25 4
gpt4 key购买 nike

我已经创建了一个 spring boot 应用程序并且一直在使用 H2 嵌入式数据库。哪个工作正常。

但是,我添加了application.properties 文件并添加了对postgresql 的依赖。这也可以正常工作,但是当我必须测试我的应用程序时,我想使用嵌入式数据库启动它。除了删除 application.properties 文件外,我看不到任何其他方法,这不是一种非常巧妙的方法。

我希望标志 spring.datasource.initialization-mode=embedded 会让它加载嵌入式数据库,但它完全忽略了它。

有没有一种方法可以通过打开和关闭标志来实现这一点?

我正在使用 gradle 作为构建工具。如果可以通过 gradle 实现这一点,那就太好了。

最佳答案

除了@Isank 所说的之外,这在您想要使用内存数据库或只是不同的数据库运行应用程序(不是单元/集成测试,但可能是手动测试)的情况下可能很有用。

您可以定义配置文件,并且对于每个配置文件,您可以拥有不同的应用程序属性。使用命名约定,假设您有三个环境(开发、生产、测试​​),您定义了三个不同的属性文件:

application-dev.properties
application-prod.properties
application-test.properties

您需要将所有这些文件放在 src/main/resources/ 中,以便自动获取它们。或者,您需要通过传递运行时参数 --spring.config.location 来告诉 spring-boot 属性文件的位置。

现在,有了所有这些文件,你如何告诉 spring-boot 使用哪一个?

如果您的属性文件是根据约定 application-{profile}.properties 命名的,那么您可以通过传递 --spring.profiles.active={profile} 参数。

  1. 运行jar 文件
java -jar spring-boo-app-name.jar --spring.profiles.active=prod 
//this will use the application-prod.properties file
  1. 使用bootRun gradle 任务
bootRun {
args '--spring.profiles.active=prod'
}

当您启动 spring-boot 应用程序时,您将在控制台中看到 Activity 配置文件。

enter image description here

关于java - Spring 启动 : switch between embedded and postgresql datasources by changing a flag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58507641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com