springboot获取当前项目端口
时间: 2023-06-13 11:04:02 浏览: 58
在Spring Boot中获取当前项目端口的方法有多种,以下是其中一些常用的方法:
1. 通过注入ServerProperties对象获取端口号:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Component;
@Component
public class PortGetter {
@Autowired
private ServerProperties serverProperties;
public int getPort() {
return serverProperties.getPort();
}
}
```
在上述代码中,通过注入ServerProperties对象,调用其getPort()方法即可获取当前项目的端口号。
2. 通过注入Environment对象获取端口号:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class PortGetter {
@Autowired
private Environment environment;
public int getPort() {
return Integer.parseInt(environment.getProperty("local.server.port"));
}
}
```
在上述代码中,通过注入Environment对象,调用其getProperty()方法获取当前项目的端口号。
3. 通过注入HttpServletRequest对象获取端口号:
```java
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component
public class PortGetter {
@Autowired
private HttpServletRequest request;
public int getPort() {
return request.getLocalPort();
}
}
```
在上述代码中,通过注入HttpServletRequest对象,调用其getLocalPort()方法获取当前项目的端口号。
以上是三种常用的获取当前项目端口的方法,具体使用哪种方法取决于具体的场景和需求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)