SpringBoot2.2.x gets the ip and port number of the project
- Write service class
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();
}
}
- Business layer injection call
@Autowired
private ServerConfig serverConfig;
public String getUrl() {
return serverConfig.getUrl();
}
Reprint address: https://blog.csdn.net/mibi8840/article/details/83824134