繁体   English   中英

启动时如何配置Spring Boot Application在特定数据库上运行

[英]How to configure Spring Boot Application to run on a specific database when launching

我有一个用Spring Boot开发的Spring MVC应用程序。 顺便说一句,此应用程序仅用于学习目的。

默认情况下,该应用程序启动并使用MySQL数据库。 对于单元和集成测试,我使用内存中的H2数据库,它可以完美运行。

因此,我有两个application.properties。 其中一个在/src/main/resources/application.properties下。

spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost/myDatabase
spring.datasource.username = root
spring.datasource.password = mysql

spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false

/src/test/resources/application.properties下的另一个application.properties

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"
spring.datasource.username=sa
spring.datasource.password=sa

现在,我必须使用Selenium进行自动化的网站测试,并且我不希望在MySQL数据库中填充测试数据。

我以前在Spring尚未做过,但是我希望我的应用程序可以这样工作:

  • 使用某些命令从终端启动我的应用程序,以指定应使用的数据库。 它应该在localhost:8080上启动
  • 然后,在localhost:8080中运行所有Selenium测试。 只要应用程序正在运行,Selenium测试生成的所有数据都将保留在内存中

如何在Spring Boot应用程序中使用application.properties或其他配置执行此操作?

Spring应该自动为您执行此操作。 在运行测试时从src / test / resources运行application.properties,因为spring使用“ test”配置文件运行。 如果没有,请在测试类上添加@ActiveProfiles("test")批注(这是指您要进行测试的类,而不是被测类)。 如果仍然无法解决问题,则可以将src / test / resources / application.properties重命名为src / test / resources / application-test.properties并在运行配置中选择配置文件(有一个名为“ profile”的字段)。 参考更多信息

  1. 创建一个名为application-test.properties的单独属性文件,并将其放在/src/test/resources 测试数据库属性(或任何其他测试特定的属性)应在此处。
  2. 在测试类的顶部,使用此批注@ActiveProfiles("test")

     @ActiveProfiles("test") public class MyTest { ... } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM