import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Configuration; import org.springframework.util.Assert; /** * @author jiangzeyin * @create 2017 02 14 12:44 */ @Configuration public class ServiceInfoUtil implements ApplicationListener<EmbeddedServletContainerInitializedEvent> { private static EmbeddedServletContainerInitializedEvent event; @Override public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) { ServiceInfoUtil.event = event; } public static int getPort() { Assert.notNull(event); int port = event.getEmbeddedServletContainer().getPort(); Assert.state(port != -1, "端口号获取失败"); return port; } }
这是Spring Boot 2.0.0 M1之前获取本项目端口的方法
然而在Spring Boot 2.0.0 M1之后,EmbeddedServletContainerInitializedEvent已经改名
我们参考https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M4-Release-Notes
中说道:
Embedded containers package structure
In order to support reactive use cases, the embedded containers package structure has been refactored quite extensively. EmbeddedServletContainer has been renamed to WebServer and the org.springframework.boot.context.embedded package has been relocated to org.springframework.boot.web.embedded. For instance, if you were customizing the embedded Tomcat container using the TomcatEmbeddedServletContainerFactory callback interface, you should now use TomcatServletWebServerFactory.
EmbeddedServletContainer 已经改名为WebServer 了
所以新代码如下:
import org.springframework.boot.web.context.WebServerInitializedEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class IpConfiguration implements ApplicationListener<WebServerInitializedEvent> { private int serverPort; @Override public void onApplicationEvent(WebServerInitializedEvent event) { this.serverPort = event.getWebServer().getPort(); } public int getPort() { return this.serverPort; } }