動態獲取tomcat啟動埠,控制檯列印專案訪問地址

Moshow鄭鍇發表於2020-04-07

前言

正常我們輸出專案的訪問地址,都是通過在@SpringBootApplication的啟動類中增加一個log.info來輸出專案地址.感謝網友@Gao Hang Hang 則為我們帶來一個動態獲取tomcat埠的改造.非常有意思,所以share一下.

原始方法

package com.softdev.system.generator;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * https://github.com/moshowgame/SpringBootCodeGenerator
 * @Author zhengkai.blog.csdn.net
 **/
@SpringBootApplication
public class GeneratorWebApplication {
	public static void main(String[] args) {
		SpringApplication.run(GeneratorWebApplication.class,args);
		log.info("專案啟動啟動成功!訪問地址: http://localhost:1234/generator");
	}
}

動態改造

package com.softdev.system.generator.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @Description 動態獲取tomcat啟動埠,控制檯列印專案訪問地址
 * @Author Gao Hang Hang
 * @Date 2019-12-27 14:37
 **/
@Component
@Slf4j
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {

    private int serverPort;

    public int getPort() {
        return this.serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
        //log.info("Get WebServer port {}", serverPort);
        log.info("專案啟動啟動成功!訪問地址: http://localhost:{}/generator", serverPort);
    }

}

相關文章