@Component
@Slf4j
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {

    private int serverPort;

    public int getPort() {
        return this.serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

    // 获取项目IP
    public String getIp() throws UnknownHostException {

        InetAddress address = InetAddress.getLocalHost();
        return address.getHostAddress();
    }

    /**
     * 放到外部tomcat中部署的时候,就需要剔除内置的tomcat容器,此时Springboot的启动流程就和上面不一样
     * @return
     */
    public int getTomcatPort() {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            QueryExp protocol = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));
            ObjectName name = new ObjectName("*:type=Connector,*");
            Set<ObjectName> objectNames = beanServer.queryNames(name, protocol);
            for (ObjectName objectName : objectNames) {
                String catalina = objectName.getDomain();
                if ("Catalina".equals(catalina)) {
                    return Integer.parseInt(objectName.getKeyProperty("port"));
                }
            }
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

使用时:serverConfig.getPort()