动态获取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);
    }

}
发布了293 篇原创文章 · 获赞 401 · 访问量 111万+

猜你喜欢

转载自blog.csdn.net/moshowgame/article/details/103761894
今日推荐