12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
建站问答 时间:2024-12-01 12:55:05
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在Spring Boot中,可以通过注入ServerProperties来获取服务器的IP和端口号。具体步骤如下:在application.properties或application.yml配置文件中,设置服务器端口号(如果已经设置
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在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();}}
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和端口号。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19