Spring Boot 3中以server.port=0启动后如何获取实际服务端口?
在Spring Boot 3中获取动态绑定的服务器端口(应用不可修改)
假设通过以下方式编程启动Spring Boot 3应用:
ConfigurableApplicationContext ctx = SpringApplication.run(MyApplication.class, new String[]{"--server.port=0", ...});
启动后服务器会绑定到一个随机可用端口,需要获取该端口值。在Spring Boot 2中可以通过以下代码获取:
return (Integer) ((Map) ctx.getEnvironment() .getPropertySources().get("server.ports").getSource()) .get("local.server.port");
但该方法在Spring Boot 3.1.3中无法生效。
更新说明:应用不可修改,无法通过注入值的方式获取端口,必须从ConfigurableApplicationContext中获取信息,或更换启动方式。
方法1:直接从WebServer实例获取端口
Spring Boot 3中可以直接从应用上下文获取WebServer实例,从中提取绑定的端口:
WebServer webServer = ctx.getBean(WebServer.class); int port = webServer.getPort();
该方式适配所有Servlet/Reactive类型的Web服务器(Tomcat、Jetty、Undertow等),只要应用成功启动服务器,就能拿到正确端口。
方法2:通过Environment直接读取local.server.port属性
在Spring Boot 3中,local.server.port已成为Environment的直接可用属性,无需再通过内部属性源层层获取:
Integer port = ctx.getEnvironment().getProperty("local.server.port", Integer.class);
这个方法更简洁,服务器启动完成后该属性会自动填充。
方法3:通过启动监听提前获取端口(可选)
如果需要在应用启动过程中就监听端口绑定事件,可在启动时添加自定义监听器,无需修改原有应用代码:
SpringApplication app = new SpringApplication(MyApplication.class); app.addListeners((ApplicationListener<WebServerInitializedEvent>) event -> { int boundPort = event.getWebServer().getPort(); // 在此处处理端口信息,比如记录日志或传递给外部逻辑 }); ConfigurableApplicationContext ctx = app.run("--server.port=0");
内容的提问来源于stack exchange,提问作者arcuri82
相关产品推荐
相关产品推荐

