前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot / Spring Cloud 项目中获取本项目端口号

Spring Boot / Spring Cloud 项目中获取本项目端口号

作者头像
似水的流年
发布2019-12-05 18:55:06
1.2K0
发布2019-12-05 18:55:06
举报
文章被收录于专栏:电光石火电光石火
代码语言:javascript
复制
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 了

所以新代码如下:

代码语言:javascript
复制
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;
    }
}

参考文章:Spring Boot 在程序中获取启动端口号

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Embedded containers package structure
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档