Springboot中获取本机IP、端口号和Context-path,项目启动后输出路径

获取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);
    }
}
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值