Spring boot 获取当前启动端口和IP

参考:

一、获取端口
  1. 通过environment获取
@Autowired
Environment environment;

public String getPort(){
  return environment.getProperty("local.server.port");
}
  1. 通过@LocalServerPort@Value("${local.server.port}")获取
@Value("${local.server.port}")
private String port ;
@LocalServerPort
private String port ;

注:当application.yml配置文件中没有指定服务启动端口时,不能使用@LocalServerPort@Value("${local.server.port}")的方法获取端口号,只能使用environment的方式

二、获取本机ip

InetAddress localHost = null;
try {
  localHost = Inet4Address.getLocalHost();
} catch (UnknownHostException e) {
  logger.error(e.getMessage(),e);
}
String ip = localHost.getHostAddress();  // 返回格式为:xxx.xxx.xxx
// localHost.getHostName() 一般是返回电脑用户名

参考:

  • Spring Boot - How to get the running port
  • Getting the IP address of the current machine using Java
  • Get Local IP Address and Hostname In Java
  • java中获取当前服务器的Ip地址

你可能感兴趣的:(Spring boot 获取当前启动端口和IP)