如何在运行时获取SPRING Boot HOST和PORT地址?

Ane*_* L. 16 port host spring-boot

如何在运行时获取部署应用程序的主机和端口,以便我可以在我的java方法中使用它?

Ant*_*hin 20

您可以通过Environment以下方式获取此信息port,host您可以通过使用获得InternetAddress.

@Autowired
Environment environment;

......
public void somePlaceInTheCode() {
    // Port
    environment.getProperty("server.port");
    // Local address
    InetAddress.getLocalHost().getHostAddress();
    InetAddress.getLocalHost().getHostName();

    // Remote address
    InetAddress.getLoopbackAddress().getHostAddress();
    InetAddress.getLoopbackAddress().getHostName();
}
Run Code Online (Sandbox Code Playgroud)

  • 在使用随机端口(`server.port=0`)的情况下,使用`local.server.port` 代替`server.port` 将是更好的选择。 (3认同)
  • 只有在以下情况下才能以这种方式获取端口:a)端口实际上已显式配置,并且b)未设置为0(意味着servlet容器在启动时将选择一个随机端口)。为了获得实际的端口,您需要实现ApplicationListener <EmbeddedServletContainerInitializedEvent>并从提供的事件中获取端口。 (2认同)

小智 11

如果您使用类似随机端口的server.port=${random.int[10000,20000]}方法。Environment并在 Java 代码中读取正在使用的端口@ValuegetProperty("server.port"). 您将得到一个不可预测的端口,因为它是随机的。

ApplicationListener,您可以重写 onApplicationEvent 以获取设置后的端口号。

在 Spring boot 版本中实现 Spring 接口ApplicationListener<EmbeddedServletContainerInitializedEvent>(Spring boot 版本 1)或ApplicationListener<WebServerInitializedEvent>(Spring boot 版本 2)覆盖 onApplicationEvent 以获取 Fact Port 。

弹簧靴1

@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
    int port = event.getEmbeddedServletContainer().getPort();
}
Run Code Online (Sandbox Code Playgroud)

弹簧靴2

@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
    Integer port = event.getWebServer().getPort();
    this.port = port;
}
Run Code Online (Sandbox Code Playgroud)