springboot获取服务端口

Springboot项目再启动的过程中依次发布的事件为:

1
2
3
4
class .springframework.context.event.ContextRefreshedEvent
class .springframework.boot.web.servlet.context.**ServletWebServerInitializedEvent**
class .springframework.boot.context.event.ApplicationStartedEvent
class .springframework.boot.context.event.ApplicationReadyEvent

1
2
3
4
5
6
7
8
9

public class MyListener implements ApplicationListener<ServletWebServerInitializedEvent> {

@Override
public void onApplicationEvent(ServletWebServerInitializedEvent servletWebServerInitializedEvent) {
int port = servletWebServerInitializedEvent.getWebServer().getPort();
System.out.println(port);
}
}