动态获取tomcat启动端口,控制台打印项目访问地址

前言

正常我们输出项目的访问地址,都是通过在@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);
    }

}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 博客之星2020 设计师:CY__ 返回首页