You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成H2内存数据库测试时,如何禁用data.sql的数据自动插入

当然可以!在Spring Boot项目里,你有好几种灵活的方式来在测试期间禁用data.sql的初始数据插入,我给你分享几个最常用的方案:

方案1:通过测试类属性直接禁用

在你的测试类上添加@TestPropertySource注解,直接清空data.sql的加载路径,这样Spring Boot就不会去读取并执行这个文件了:

@TestPropertySource(properties = "spring.sql.init.data-locations=")
@SpringBootTest
public class YourEntityTest {
    // 你的测试逻辑
}

注意:如果你的Spring Boot版本低于2.5.x,对应的属性是spring.datasource.data=,需要替换成这个旧属性名。

方案2:使用@Sql注解精准控制初始化脚本

如果你的测试仍然需要执行schema.sql来创建表结构,但不想加载data.sql,可以用@Sql注解明确指定只执行表结构脚本:

@SpringBootTest
@Sql(scripts = "classpath:schema.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
public class YourEntityTest {
    // 这里只会执行schema.sql创建表,不会自动加载data.sql
}

这种方式的好处是可以精准控制每个测试类的初始化行为,适合只在个别测试中禁用data.sql的场景。

方案3:通过测试Profile全局配置

如果所有测试都需要禁用data.sql,可以创建测试专属的配置文件来统一设置:

  1. 在src/test/resources下创建application-test.properties文件,添加配置:
# 禁用data.sql的自动执行
spring.sql.init.data.enabled=false
# 确保schema.sql仍然正常执行(如果需要的话)
spring.sql.init.schema.enabled=true
  1. 在测试类上激活这个test Profile:
@SpringBootTest
@ActiveProfiles("test")
public class YourEntityTest {
    // 你的测试逻辑
}

这种方式适合全局统一配置测试环境的初始化行为,避免在每个测试类重复设置。

小提示:如果是Spring Boot 2.4及更早版本,对应的属性是spring.datasource.data=(设为空字符串),不过更推荐用新版本的spring.sql.init.*属性,这是官方推荐的新配置方式。

内容的提问来源于stack exchange,提问作者Kojod88

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:12:44