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)
小智 11
如果您使用类似随机端口的server.port=${random.int[10000,20000]}方法。Environment并在 Java 代码中读取正在使用的端口@Value或getProperty("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)
| 归档时间: |
|
| 查看次数: |
27834 次 |
| 最近记录: |