溫馨提示×

springboot如何獲取服務器ip和端口號

小億
1522
2023-08-09 10:22:33
欄目: 云計算

在Spring Boot中,可以通過注入ServerProperties來獲取服務器的IP和端口號。具體步驟如下:

  1. application.propertiesapplication.yml配置文件中,設置服務器端口號(如果已經設置,可以跳過此步驟):
server.port=8080
  1. 創建一個類,并注入ServerProperties
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Component;
@Component
public class ServerInfo {
private final ServerProperties serverProperties;
@Autowired
public ServerInfo(ServerProperties serverProperties) {
this.serverProperties = serverProperties;
}
public String getServerAddress() {
return serverProperties.getAddress().getHostName();
}
public int getServerPort() {
return serverProperties.getPort();
}
}
  1. 在需要獲取服務器IP和端口號的地方,注入ServerInfo類,并調用相應的方法:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private final ServerInfo serverInfo;
@Autowired
public MyController(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
@GetMapping("/info")
public String getInfo() {
String serverAddress = serverInfo.getServerAddress();
int serverPort = serverInfo.getServerPort();
return "Server IP: " + serverAddress + ", Server Port: " + serverPort;
}
}

這樣,當訪問/info接口時,將返回服務器的IP和端口號。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女