Spring Boot集成H2数据库遇阻:无法查看控制台、修改端口及持久化问题
Hey there! Let's work through these H2 + Spring Boot issues step by step—you've got this. I've been in your shoes before, so let's break down each requirement and problem one by one.
1. 实现数据持久化(重启/关机不丢失数据)
H2默认是内存模式,这就是为什么你关闭应用后数据会消失。要解决这个问题,我们需要把它配置成文件存储模式。
把这些配置添加到你的application.properties(如果习惯用YAML也可以转成对应格式):
# 数据源核心配置:持久化到本地文件 spring.datasource.url=jdbc:h2:file:./data/h2db;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=
file:./data/h2db: 指定数据库文件存在项目根目录的data文件夹下(文件夹会自动创建),你也可以换成绝对路径比如file:/Users/yourname/h2-data/mydbDB_CLOSE_ON_EXIT=FALSE: 防止应用关闭时自动断开数据库连接,避免数据写入不完整AUTO_SERVER=TRUE: 允许多个进程访问同一个数据库文件(比如同时运行应用和手动连接H2客户端)
2. 修复H2 Web控制台无法访问的问题
Spring Boot默认是禁用H2控制台的,我们需要启用它并配置访问规则:
在application.properties里添加这些:
# 启用H2 Web控制台 spring.h2.console.enabled=true # 设置控制台访问路径(可以自定义,比如改成/h2) spring.h2.console.path=/h2-console
如果你用了Spring Security(开发中很常见)
你需要放行H2控制台的访问权限,同时关闭一些会阻止其iframe界面的安全限制。创建一个安全配置类:
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 放行H2控制台的所有请求 .authorizeRequests() .antMatchers("/h2-console/**").permitAll() .anyRequest().authenticated() // 关闭CSRF保护(H2控制台不支持这个机制) .and() .csrf().ignoringAntMatchers("/h2-console/**") // 允许iframe加载H2控制台界面 .and() .headers().frameOptions().sameOrigin(); } }
3. 修改H2控制台的默认端口
H2控制台默认端口是8082,要修改的话,只需在application.properties里加一行:
# 自定义H2控制台端口(比如改成9090) spring.h2.console.port=9090
之后你就可以通过http://localhost:9090/h2-console访问控制台了(把9090换成你选的端口)。
验证步骤
- 启动你的Spring Boot应用
- 打开浏览器,访问控制台的URL(比如
http://localhost:9090/h2-console) - 在登录页面,确保JDBC URL和你在
spring.datasource.url里配置的完全一致(比如jdbc:h2:file:./data/h2db) - 输入用户名
sa,密码留空(或者你自己设置的密码) - 点击"Connect"——现在应该能看到你的数据库表了!
- 创建一个测试表,插入一些数据,然后停止并重启应用。重新连接控制台后,数据应该还在。
如果遇到奇怪的问题,先检查配置里的JDBC URL和控制台登录页的是否完全匹配——这是我见过最常见的错误!
内容的提问来源于stack exchange,提问作者Ghost Rider
相关产品推荐
相关产品推荐

