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

无Spring Web依赖的Spring Boot应用如何访问H2控制台?

H2控制台无法访问的解决方法

问题描述

我的Spring Boot应用仅引入了spring-data-jpa这一个Spring依赖,集成了H2数据库。先在application.yml中配置:

spring:
  h2:
    console:
      enable: true

尝试访问localhost:8080/h2-console、localhost:8082/、localhost:8082/h2-console均失败。之后添加路径配置:

spring:
  h2:
    console:
      enable: true
      path: /h2-console

但访问8080/h2-console、localhost:8082/h2-console依旧无法成功。询问是否可访问H2控制台,以及具体操作方法。

解决步骤

当然可以访问H2控制台,核心问题是缺少H2数据库的核心依赖,仅引入spring-data-jpa不足以支撑H2控制台运行。

  • 添加H2依赖
    根据你的构建工具添加对应依赖:
    Maven(pom.xml):

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    

    Gradle(build.gradle):

    runtimeOnly 'com.h2database:h2'
    

    runtime/runtimeOnly作用是仅在运行时引入依赖,不影响编译阶段。

  • 确认服务器端口
    检查application.yml中的server.port配置,若未自定义,Spring Boot默认使用8080端口,访问地址为http://localhost:8080/h2-console;若配置了其他端口(如8082),则替换为对应端口访问。

  • 排查权限限制(若有Spring Security)
    若应用引入了Spring Security依赖,需允许H2控制台路径的匿名访问,并开启iframe支持:

    @Configuration
    public class SecurityConfig {
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                    .requestMatchers("/h2-console/**").permitAll()
                    .anyRequest().authenticated()
            );
            http.headers(headers -> headers.frameOptions(frame -> frame.sameOrigin()));
            return http.build();
        }
    }
    
  • 验证启动状态
    启动应用后,查看控制台日志,若出现类似H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:xxxxxx'的输出,说明控制台已正常启动,直接访问日志中的路径即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:42:36