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

如何在IntelliJ中启动Spring Boot应用时自动打开Swagger页面?

实现IntelliJ启动Spring Boot后自动打开Swagger页面

完全可以实现,下面给你两种实用的方法:

方法一:通过IntelliJ运行配置设置(推荐,不侵入代码)

  • 点击IntelliJ右上角运行按钮旁的下拉菜单,选择「Edit Configurations」打开运行配置窗口
  • 找到你的Spring Boot应用对应的配置项,切换到Startup/Connection标签页,点击「Before launch」区域的「+」号,选择「Run External Tool」
  • 在弹出的窗口里再点击「+」号,新建一个外部工具:
    • 名称随便填,比如「Open Swagger Page」
    • Program栏填你常用浏览器的执行路径:
      • Windows(Chrome):C:\Program Files\Google\Chrome\Application\chrome.exe
      • Mac(Chrome):/Applications/Google Chrome.app/Contents/MacOS/Google Chrome
      • Linux(Chrome):google-chrome
    • Arguments栏填你的Swagger页面地址,比如http://localhost:8080/swagger-ui/index.html(根据实际端口和Swagger路径调整)
    • Working directory留空即可
  • 保存外部工具后,把它拖动到「Build」步骤的后面,确保应用启动完成后再打开浏览器
  • 以后启动这个Spring Boot配置时,IntelliJ会自动在应用启动后打开浏览器访问Swagger页面

方法二:代码层面实现(适合跨IDE或不想改配置的场景)

在Spring Boot项目里添加一个启动后执行的Runner组件,应用启动完成后自动调用浏览器打开Swagger:

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.awt.*;
import java.net.URI;

@Component
@Profile("dev") // 仅在开发环境生效,避免服务器环境执行
public class SwaggerAutoOpener implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            Desktop.getDesktop().browse(new URI("http://localhost:8080/swagger-ui/index.html"));
        }
    }
}

注意:这种方式依赖Java的Desktop类,在无图形界面的服务器环境下会失效,所以一定要加上@Profile("dev")限制仅开发环境启用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:45:30