如何在本地构建与单元测试中替换H2数据库为真实数据库?
如何在本地构建与单元测试中替换H2数据库为真实数据库?
嘿,我来帮你搞定这个问题!从你的描述来看,问题确实和Spring Profile有关——你的MySQL配置只在local profile下生效,而本地构建/测试时默认用的是默认profile(没指定profile时Spring会自动启用这个),这时候Spring Boot会自动配置H2内存库(因为它是Spring Boot默认的嵌入式数据库,而且通常spring-boot-starter-test依赖里会包含H2)。
下面是具体的解决步骤:
1. 让本地构建/测试激活local profile
因为你的MySQL配置都在local profile下,所以需要明确告诉Spring在本地操作时使用这个profile:
- 构建项目时:
如果用Maven,执行命令时加上profile参数:
如果用Gradle,命令是:mvn clean install -Dspring.profiles.active=local./gradlew build -Dspring.profiles.active=local - 运行单元测试时:
- 方法一:在单个测试类上添加注解,强制使用
localprofile:@ActiveProfiles("local") @SpringBootTest public class YourServiceTest { // 你的测试代码 } - 方法二:在IDE的运行配置里添加VM参数,全局激活
localprofile:
在VM options里加上:-Dspring.profiles.active=local
- 方法一:在单个测试类上添加注解,强制使用
- (可选)如果想默认就用
localprofile,可以在application.yaml顶部加上全局配置:
不过这种方式灵活性稍差,建议还是根据场景显式指定。spring: profiles: active: local
2. 修正你的application.yaml配置缩进
你提供的yaml有缩进错误,Spring Boot的配置层级很重要,正确的格式应该是这样(datasource和jpa要嵌套在spring下):
spring: config: activate: on-profile: local datasource: url: jdbc:mysql://localhost/my_database?useSSL=false&createDatabaseIfNotExist=true&useConfigs=maxPerformance&useCursorFetch=true&profileSQL=true username: root password: root jpa: show-sql: true
缩进错了的话,Spring根本读不到你的MySQL配置,自然还是用H2。
3. 确保依赖配置正确
- 首先,要添加MySQL驱动依赖:
Maven项目在pom.xml里加:
Gradle项目在<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>build.gradle里加:runtimeOnly 'mysql:mysql-connector-java' - (可选)如果不想再用H2,可以把
spring-boot-starter-test里的H2依赖排除掉,避免不必要的自动配置:
Maven:
Gradle:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </exclusion> </exclusions> </dependency>testImplementation('org.springframework.boot:spring-boot-starter-test') { exclude group: 'com.h2database', module: 'h2' }
4. 单元测试的特殊处理(如果用了@DataJpaTest等注解)
如果你用了@DataJpaTest、@AutoConfigureTestDatabase这类测试注解,Spring默认会强制使用嵌入式数据库(比如H2),这时候需要额外配置:
@DataJpaTest @ActiveProfiles("local") @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) public class YourRepositoryTest { // 你的仓库测试代码 }
@AutoConfigureTestDatabase(replace = Replace.NONE)会告诉Spring不要替换你的数据源配置,直接用local profile里的MySQL。
按照上面的步骤来,应该就能把本地构建和测试的数据库从H2换成MySQL了!
备注:内容来源于stack exchange,提问作者jb62




