SpringBoot2.2.x获取项目的ip和端口号
- 编写服务类
package com.cloud.route.V4.template.config;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
private int serverPort;
public String getUrl() {
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "http://"+ address.getHostAddress() +":"+this.serverPort;
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
this.serverPort = event.getWebServer().getPort();
}
}
- 业务层注入调用
@Autowired
private ServerConfig serverConfig;
public String getUrl() {
return serverConfig.getUrl();
}
转载地址:https://blog.csdn.net/mibi8840/article/details/83824134