增加配置类
@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;
}
}
获取ip 端口号的代码
@Autowired
IpConfiguration ip;
InetAddress address = InetAddress.getLocalHost();
System.out.println("端口号"+address.getHostAddress()+",ip:"+ip.getPort());
本文介绍了一种在SpringBoot应用中通过自定义配置类获取服务器IP地址和端口的方法。通过实现ApplicationListener接口监听WebServerInitializedEvent事件,可以在应用启动时捕获服务器的端口号,并结合InetAddress类获取本地主机的IP地址。
1091





