Spring Boot/Spring Cloudプロジェクトで本プロジェクトのポート番号を取得

4037 ワード

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 {
    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 M 1より前に本プロジェクトのポートを取得する方法ですが、Spring Boot 2.0.0 M 1より後にE m b e d d e d e d e d e d S v e r t ContainerInitializedEventが名前を変更しました.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.
EmbeddedServiceletContainerはWebServerに名前を変更しました
新しいコードは次のとおりです.
package com.anur.messageserver.config;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * Created by Anur IjuoKaruKas on 2018/5/8
 */
@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プログラムで起動ポート番号を取得する