You can access the port the server is running on from log output or
from the ServletWebServerApplicationContext through its WebServer.
The best way to get that and be sure that it has beenn initialized
is to add a @Bean of type ApplicationListener <ServletWebServerInitializedEvent>
and pull the container out of the event when it is published.
文档里说,最好使用ServletWebServerInitializedEvent
的事件推送来获取,因为如果不是Web应用,去获取ServletWebServerApplicationContext,肯定是不严谨的。
public class ServletWebServerInitializedEvent extends WebServerInitializedEvent {
private final ServletWebServerApplicationContext applicationContext;
public ServletWebServerInitializedEvent(WebServer webServer, ServletWebServerApplicationContext applicationContext) {
super(webServer);
this.applicationContext = applicationContext;
}
public ServletWebServerApplicationContext getApplicationContext() {
return this.applicationContext;
}
}
翻译一下这个事件:ServletWebServerInitializedEvent
Servlet容器Web服务器初始化事件。该类继承了WebServerInitializedEvent
用这个事件的前提肯定是,选择使用的是Servlet Web容器,而不是Reactive Web容器。所以监听父类事件WebServerInitializedEvent
所覆盖的范围会更广。
Servlet Web容器下又分了3种服务器,Tomcat,Jetty,undertow
Reactive Web容器下,默认是NettyWebServer ,当然也可以替换成上述三种。
@SpringBootApplication
public class XXXApplication {
@EventListener(WebServerInitializedEvent.class)
public void xxxx(WebServerInitializedEvent event){
System.out.println(“运行时HTTP端口为:”+event.getWebServer().getPort());
}
}