比较通用的方法是:
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@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();
}
}
要调用的时候只需要注入
还有,如果你的在application.properties中配置了端口地址
那获取端口号是就更简单了只需要就能按需使用了
@Value("${server.port}")
private int serverPort;