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

SpringBoot如何获取应用完整URL?非嵌入式Web服务器场景适配

实现SpringBoot API全生命周期事件记录(兼容任意Web服务器)

完全可以实现,SpringBoot本身提供了一套不依赖具体Web服务器的通用生命周期事件机制,不管你用Tomcat、Jetty还是Undertow,都能通过监听内置事件完成需求。

核心方案:监听SpringBoot通用生命周期事件

通过自定义监听器捕获关键事件,即可记录从启动到关闭的全流程信息,包括你需要的服务启动地址。

1. 自定义事件监听器代码

创建一个Spring组件,用@EventListener注解监听目标事件:

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class AppLifecycleLogger {

    // 监听Web服务器初始化完成(获取监听端口)
    @EventListener(WebServerInitializedEvent.class)
    public void logServerPort(WebServerInitializedEvent event) {
        int port = event.getWebServer().getPort();
        System.out.println("Web server initialized, listening on port: " + port);
    }

    // 监听应用完全就绪(输出完整启动地址)
    @EventListener(ApplicationReadyEvent.class)
    public void logAppReady(ApplicationReadyEvent event) {
        try {
            String hostIp = InetAddress.getLocalHost().getHostAddress();
            int port = event.getApplicationContext().getBean(org.springframework.boot.web.server.WebServer.class).getPort();
            String contextPath = event.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path", "");
            
            String fullStartupUrl = String.format("App started at http://%s:%s%s", hostIp, port, contextPath);
            System.out.println(fullStartupUrl);
        } catch (UnknownHostException e) {
            System.err.println("Failed to get local host IP: " + e.getMessage());
        }
    }

    // 监听应用关闭事件
    @EventListener(ContextClosedEvent.class)
    public void logAppShutdown(ContextClosedEvent event) {
        System.out.println("Application is shutting down...");
    }
}

2. 关键事件说明

这些事件是SpringBoot的通用事件,所有Web服务器都会触发:

  • WebServerInitializedEvent:Web服务器初始化完成时触发,此时已能获取监听端口
  • ApplicationReadyEvent:应用完全就绪(所有Bean初始化完成),此时可以安全拼接完整访问地址
  • ContextClosedEvent:应用开始关闭时触发,用于记录停止日志

3. 扩展:记录更多生命周期阶段

如果需要覆盖更多流程,还可以监听这些事件:

  • ApplicationStartingEvent:应用刚启动时触发
  • ApplicationEnvironmentPreparedEvent:环境变量加载完成时触发
  • ApplicationPreparedEvent:上下文准备完成,但Bean未初始化时触发

注意事项

  • 若应用部署在集群或使用反向代理,InetAddress.getLocalHost()可能返回内网IP,可根据部署环境从环境变量或配置中心获取公网IP
  • 上下文路径server.servlet.context-path未配置时默认是空字符串,不影响地址拼接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:33:17