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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章