Spring Boot集成H2数据库时控制台无法访问问题
H2数据库运行正常但控制台无法访问的问题排查
我按照教程集成Spring Boot与H2数据库,数据库本身运行正常,但H2控制台始终无法打开。已多次调整配置,当前相关配置如下:
application.properties 配置
#Database settings spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=root spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.data.jpa.repositories.bootstrap-mode=default spring.h2.console.enabled=true spring.h2.console.settings.web-allow-others=true spring.datasource.generate-unique-name = false spring.h2.console.path=/h2-console/ spring.jpa.hibernate.ddl-auto=update spring.datasource.tomcat.connection-properties=useUnicode=true;characterEncoding=utf-8; spring.datasource.sql-script-encoding=UTF-8 spring.jpa.open-in-view=false spring.datasource.initialization-mode=always #swagger spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER #Disable thymeleaf cashing spring.template.cache = false;
Gradle 依赖配置
ext { spring_boot_version = '2.6.6' } implementation "org.springframework.boot:spring-boot-starter-parent:${spring_boot_version}" implementation "org.springframework.boot:spring-boot-starter-data-jpa:${spring_boot_version}" implementation "org.springframework.boot:spring-boot-starter-validation:${spring_boot_version}" implementation "org.springframework.boot:spring-boot-starter-thymeleaf:${spring_boot_version}" implementation "org.springframework.boot:spring-boot-starter-web:${spring_boot_version}" runtimeOnly "com.h2database:h2:1.4.193"
尝试访问地址:http://localhost:8080/h2-console,无法打开控制台页面。
排查与解决建议
- 路径匹配问题:配置中
spring.h2.console.path=/h2-console/末尾带斜杠,而访问地址是/h2-console,尝试访问http://localhost:8080/h2-console/(带末尾斜杠),或者修改配置将路径改为/h2-console(去掉末尾斜杠)。 - H2版本兼容问题:当前使用的H2版本1.4.193与Spring Boot 2.6.6适配性不足,建议升级到兼容版本,比如
2.1.214,修改依赖为:runtimeOnly "com.h2database:h2:2.1.214" - 拦截器/安全配置拦截:如果项目中引入了Spring Security,需添加H2控制台路径的放行规则:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/h2-console/**").permitAll() .and() .csrf().ignoringAntMatchers("/h2-console/**") .and() .headers().frameOptions().sameOrigin(); } } - 确认控制台初始化状态:启动项目时查看日志,确认是否存在
H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'这类日志,若没有则说明控制台未正确启用,检查spring.h2.console.enabled=true是否被其他配置覆盖。 - 端口验证:确认项目确实运行在8080端口,未被
server.port等配置修改端口号。
内容的提问来源于stack exchange,提问作者hhrzc
相关产品推荐
相关产品推荐

