springboot如何获取服务器ip和端口号
在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;@Componentpublic class ServerInfo {private final ServerProperties serverProperties;@Autowiredpublic ServerInfo(ServerProperties serverProperties) {this.serverProperties = serverProperties;}public String getServerAddress() {return serverProperties.getAddress().getHostName();}public int getServerPort() {return serverProperties.getPort();}}
- 在需要获取服务器IP和端口号的地方,注入
ServerInfo
类,并调用相应的方法:import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class MyController {private final ServerInfo serverInfo;@Autowiredpublic 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和端口号。
下一篇:sql中casewhen怎么使用
SpringBoot 服务器
webacc.exe是什么文件?webacc.exe是不是病毒
WINSYS.vbs是什么文件?WINSYS.vbs是不是病毒
winssh.exe是什么文件?winssh.exe是不是病毒
wt.exe是什么文件?wt.exe是不是病毒
winsysetm.exe是什么文件?winsysetm.exe是不是病毒
winstrve.exe是什么文件?winstrve.exe是不是病毒
winsysupd7.exe是什么文件?winsysupd7.exe是不是病毒
winsysupd.exe是什么文件?winsysupd.exe是不是病毒
winsysupd2.exe是什么文件?winsysupd2.exe是不是病毒
winsysupd8.exe是什么文件?winsysupd8.exe是不是病毒