spring boot 1.3.7版本,直接从environment中获取端口,这种情况下,不管是否修改默认端口,都可以获取到。
package com.cr949.auto.docs.config;
import com.cr949.auto.docs.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.net.Inet4Address;
import java.net.InetAddress;
/**
* @author cr949
* @description spring boot 1.3.7版本 获取ip和port
* 从Environment中获取port
*/
@Slf4j
@Component
public class GetAppIpBaseSpringboot137Config {
@Autowired
private Environment environment;
/**
* spring boot 1.3.7版本获取ip的方式
* @return
*/
public String getUrl() {
InetAddress localHost = null;
try {
localHost = Inet4Address.getLocalHost();
} catch (Exception e) {
log.error("GetAppIpBaseSpringboot137Config000 error ", e);
}
String port = environment.getProperty("local.server.port");
return Constants.HTTP_PREFIX + localHost.getHostAddress() + Constants.EN_COLON + port + Constants.SWAGGER2_API_DOCS;
}
}
spring boot 2.2.6版本,直接从WebServerInitializedEvent事件中获取port中获取端口,这种情况下,不管是否修改默认端口,都可以获取到。
package com.cr949.auto.docs.config;
import com.cr949.auto.docs.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
/**
* @author cr949
* @description spring boot 2.2.6版本 获取ip和port
* 从WebServerInitializedEvent事件中获取port
*/
@Slf4j
@Component
public class GetAppIpBaseSpringboot226Config implements ApplicationListener<WebServerInitializedEvent> {
/**
* 端口号
*/
private int serverPort;
/**
* spring boot 2.2.6版本获取ip的方式
* @return
*/
public String getUrl() {
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (Exception e) {
log.error("GetAppIpBaseSpringboot226Config000 getUrl999 error ", e);
}
log.debug("ip:{}, port:{}", address.getHostAddress(), this.serverPort);
return Constants.HTTP_PREFIX + address.getHostAddress() + Constants.EN_COLON + this.serverPort + Constants.SWAGGER2_API_DOCS;
}
@Override
public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
this.serverPort = webServerInitializedEvent.getWebServer().getPort();
}
}