How to get local server host and port in Spring Boot?

后端 未结 9 1233
野性不改
野性不改 2020-12-09 02:27

I\'m starting up a Spring Boot application with mvn spring-boot:run.

One of my @Controllers needs information about the host and port the a

9条回答
  •  青春惊慌失措
    2020-12-09 03:18

    IP Address

    You can get network interfaces with NetworkInterface.getNetworkInterfaces(), then the IP addresses off the NetworkInterface objects returned with .getInetAddresses(), then the string representation of those addresses with .getHostAddress().

    Port

    If you make a @Configuration class which implements ApplicationListener, you can override onApplicationEvent to get the port number once it's set.

    @Override
    public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
        int port = event.getEmbeddedServletContainer().getPort();
    }
    

提交回复
热议问题