1. 启动时获取
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class AdminApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(AdminApplication.class);
Environment env = app.run( args).getEnvironment();
System.out.println(env.getProperty("server.port"));
}
}
2. ApplicationListener接口
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;
@Configuration
public class ServiceConfig implements ApplicationListener<WebServerInitializedEvent> {
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
ServiceConfig.serverPort = event.getWebServer().getPort();
}
private static int serverPort;
public static int getServerPort() {
return serverPort;
}
public void setServerPort(int serverPort) {
ServiceConfig.serverPort = serverPort;
}
public static String getBaseUrl() {
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "http://"+address.getHostAddress() +":"+ getServerPort();
}
}