獲取IP
直接使用InetAddress:
String IP = InetAddress.getLocalHost().getHostAddress();
獲取端口號
1.使用配置文件獲取(可能返回爲空)
Environment env = context.getEnvironment();
String port = env.getProperty("server.port");
或者
@Data
@Configuration
public class MyConfig {
@Value("${server.port}")
private int port;
}
2.通過ApplicationListener
接口(會返回實際使用的端口號)
@Component
@Slf4j
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
int serverPort = event.getWebServer().getPort();
log.info("server port {}", serverPort);
}
}
獲取Context-path
Environment env = context.getEnvironment();
String path = env.getProperty("server.servlet.context-path");
或者
@Data
@Configuration
public class MyConfig {
@Value("${server.servlet.context-path}")
private String path;
}
啓動完成輸出路徑
在Springboot啓動完成後輸出訪問路徑:
@Slf4j
@SpringBootApplication
public class MyApplication implements ApplicationListener<WebServerInitializedEvent> {
public static void main(String[] args) {
SpringApplication.run(ArrangingCoursesApplication.class, args);
}
@SneakyThrows
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
WebServer server = event.getWebServer();
WebServerApplicationContext context = event.getApplicationContext();
Environment env = context.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
int port = server.getPort();
String contextPath = env.getProperty("server.servlet.context-path");
if (contextPath == null) {
contextPath = "";
}
log.info("\n---------------------------------------------------------\n" +
"\tApplication is running! Access address:\n" +
"\tLocal:\t\thttp://localhost:{}" +
"\n\tExternal:\thttp://{}:{}{}" +
"\n---------------------------------------------------------\n", port, ip, port, contextPath);
}
}