在Spring Boot中,可以通過注入ServerProperties
來獲取服務器的IP和端口號。具體步驟如下:
application.properties
或application.yml
配置文件中,設置服務器端口號(如果已經設置,可以跳過此步驟):server.port=8080
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();
}
}
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和端口號。