获取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);
}
}