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