参考:通过Spring boot编码获取当前程序运行的host和端口号_不当初-CSDN博客

这里总共涉及,两种不同启动方式下的获取方法,

分别是Springboot以内置的tomcat启动和以外部tomcat方式启动

第一种,当Springboot以内置的tomcat启动的时候,直接采用Spring提供的ApplicationListener接口来监听项目的启动,在启动的时候获取到项目的端口号即可。

1)代码如下:

import lombok.Getter;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;/*** @className: ServerConfig* @author: wang* @date: 2021/12/7**/
@Getter
@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {private Integer port;@Overridepublic void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {this.port = webServerInitializedEvent.getWebServer().getPort();}
}

这个代码记得加上@Component或者@Configuration等注解。

使用的时候,需要用注解的方式装配对象,new实例出来的会报错

这种方式获取到的端口号,其实就是写在application配置文件中的端口号。与其这样获取,不如直接使用@Value注解去配置文件中获取。

如果要想拿到tomcat的端口号

可以采用下面这种方式,但这种方式拿到的都是内置tomcat的端口号,默认都是8080,意义不大

package com.piesat.config;import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;/*** @className: WebServerConfig* @author: wang* @date: 2021/12/7**/
@Component
@Data
public class TomcatServerConfig {private static final Logger logger = LoggerFactory.getLogger(TomcatServerConfig.class);private Integer serverPort;@Beanpublic WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {return factory -> {int serverPort = factory.getWebServer().getPort();TomcatServerConfigHolder.webServerConfig.setServerPort(serverPort);logger.error(">>>>>>>>>>>>>>>>>>port:[{}]<<<<<<<<<<<<<<<<<<", serverPort);};}private TomcatServerConfig() {}private static class TomcatServerConfigHolder {private static final TomcatServerConfig webServerConfig = new TomcatServerConfig();}public static TomcatServerConfig getInstance() {return TomcatServerConfigHolder.webServerConfig;}}

2)如果不想使用注解的方式,可以采用静态内部类的方式(对应图一)。


import lombok.Data;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;/*** @className: ServerConfig* @author: wang* @date: 2021/12/7**/@Component
@Data
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {private Integer serverPort;@Overridepublic void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {int port = webServerInitializedEvent.getWebServer().getPort();ServerConfigHolder.serverConfig.setServerPort(port);}private ServerConfig() {}private static class ServerConfigHolder {private static final ServerConfig serverConfig = new ServerConfig();}public static ServerConfig getInstance() {return ServerConfigHolder.serverConfig;}
}

使用的方法如下,效果一样

上面这种写法,只适合springboot2.0之后,1.+没有WebServerInitializedEvent类,需要换成EmbeddedServletContainerInitializedEvent

因为2.0之后,Springboot就将EmbeddedServletContainerInitializedEvent 给修改成WebServerInitializedEvent

简单的示例如下,也可以修改成上面静态内部类的方式

import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;/*** @className: ServerConfig* @date: 2021/12/7* spring boot 1.5.X**/
@Component
public class ServerConfig implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {private Integer port;@Overridepublic void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {this.port = event.getEmbeddedServletContainer().getPort();}public Integer getPort(){return port;}
}

第二种、当Springboot,打成War包,放到外部tomcat中部署的时候,就需要剔除内置的tomcat容器,此时Springboot的启动流程就和上面不一样,好像就不再有初始化WebServer的步骤了,详细步骤需要看下源码。

这个时候,项目的端口就取决于外部的tomcat配置文件是如何配置的了。

代码如下:

import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.Set;/*** @className: TomcatPortConfig * @author: wang* @date: 2021/12/7**/
public class TomcatPortConfig {public static String getPort() {MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();try {QueryExp protocol = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));ObjectName name = new ObjectName("*:type=Connector,*");Set<ObjectName> objectNames = beanServer.queryNames(name, protocol);for (ObjectName objectName : objectNames) {String catalina = objectName.getDomain();if ("Catalina".equals(catalina)) {return objectName.getKeyProperty("port");}}} catch (MalformedObjectNameException e) {e.printStackTrace();}return null;}
}

这两种方式,第一个适用于采用java -jar ***.jar的方式部署的,第二种适合,采用打成War包,部署到tomcat中进行启动的。方法不能搞反,否则都报空指针异常

SpringBoot动态获取项目部署的端口号相关推荐

  1. QT udp自动获取对方ip和端口号

    Tip: 用printf打印QString方法如下: QString output printf("%s\n",output.toStdString().data()); 正文:Q ...

  2. Java中动态获取项目根目录和tomcat的绝对路径

    序言 在开发过程中经常会用到读写文件,其中就必然涉及路径问题.使用固定的绝对路径当然很方便,但会导致程序的可移植性差,比如在代码中写死了要在E盘建一个文件,而移植后的环境中木有E盘,那就只能改代码:又 ...

  3. Docker部署项目更改Mysql端口号

    问题情景: 师弟在阿里云服务器上通过Tomcat部署java Web项目 程序端口8080 mysql端口3306 我通过Dokcer部署了前后端分离项目,为了避免端口冲突,服务器6612:3306映 ...

  4. 两个Java项目使用同一个端口号

    引言 最近是部署两个项目的时候需要使用相同的端口号,但是这两个项目却不能将代码合并,真是个头大的问题,上网上搜也搜不到好的方法 我的环境是windows 注意: 首先你这两个项目中最好不要有相同的路由 ...

  5. 百度ueditor编辑器动态获取项目根目录

    编辑器的 jsp\config.json 文件里面有个 imageUrlPrefix 这里指定的是"上传图片访问路径前缀",即项目根目录,如果是跨域(远程)操作的话,需要写上服务器 ...

  6. netstat -anp |awk |cut 通过pid获取应用程序的端口号

    脚本如下 #下列 | 表示接续处理. netstat -anopt |grep $pid|head -n 1|awk '{printf $4}'|cut -d: -f4 脚本解释 netstat -a ...

  7. Springboot实战:项目部署

    目录 一.Eclipse打包项目 二.准备Shell脚本 三.将jar包和app.sh文件上传至服务器 四.运行app.sh脚本 五.查看项目是否启动成功 六.干掉已经启动的进程 七.部署过程中可能遇 ...

  8. jsp 获取服务器ip 以及端口号

    <a href=<%="http://"+request.getLocalAddr()+":"+request.getLocalPort()+&qu ...

  9. 阿里云 部署SpringBoot和Vue项目 亲测可用(第一次部署经验贴)

    阿里云 部署SpringBoot和Vue项目 亲测可用!第一次部署经验贴! 前言:与伙伴一起写了一个项目,但是由于老师要我们部署到服务器上,而我从未有部署过,查看了csdn很多博客,试了好多篇,才成功 ...

  10. idea 启动选择profiles_玩转SpringBoot 2 之项目启动篇

    SpringBoot 启动方式有哪些? SpringBoot 有4种方式进行启动,具体方式如下: IDEA方式启动 Eclipse 方式启动 Maven 启动方式 通过SpringBoot 程序 ja ...

最新文章

  1. 2022-2028年中国氟硅橡胶产业发展动态及投资前景分析报告
  2. php开发我的世界插件,WorldEdit/开发与API
  3. 关于某些域环境下Windows Hello无法使用的解决方法
  4. 火狐渗透测试浏览器_微软、火狐浏览器、Opera浏览器等主流平台纷纷布局IPFS:大势所趋...
  5. zabbix-server-mysql安装_zabbix server 安装部署
  6. mui 实现a锚点定位 (demo演示)【建议:仅作为参考】
  7. Python之网络爬虫(验证码、代理IP、防反爬策略、封装一个抓取页面的函数)
  8. 生命游戏 并行化_新加坡电音制作人楚晴Jasmine《困兽游戏》,讲述爱情间的博弈...
  9. vue自定义组件是.vue还是html,Vue自定义组件的四种方式示例详解
  10. Android Studio for Experts(Android Dev Summit2015)
  11. win7下用UtralISO制作U盘系统盘--UltraISO打开Ubuntu只有EFI文件夹
  12. 机器学习笔记----(1)什么是机器学习
  13. hmcl手机版下载_hmcl启动器
  14. 国内外著名PT网站大全
  15. verilog实现格雷码与二进制码的互换
  16. 手把手教你关闭iphone系统自动下载(新增IOS11描述性文件地址)
  17. oracle学习之oracle基础
  18. 15b万用表怎么测电容_万用表怎么用?福禄克15B+一机详解万用表的使用方法
  19. resample按时间聚合
  20. 超声波传感器(CHx01ICU-x0201ICU-30201) - 资源抢先看(资料获取)

热门文章

  1. 项目中如何引入阿里巴巴icon图标
  2. 屏幕小于6英寸的手机_6寸手机好不好用 手机屏幕尺寸多大合适
  3. 【图像配准】基于surf算法实现图像配准附Matlab代码
  4. MySQL闪退以及服务中没有MySQL和MySQL 服务无法启动。系统出错。发生系统错误 1067。 进程意外终止。
  5. 开箱即用——用模板快速上线一个HR 服务中心
  6. 论文查重 降重复度?如何进行毕业论文查重--总结贴
  7. vscode的pip安装
  8. 【洛谷试炼场】洛谷新手村——洛谷的第一个任务
  9. Debian 10 开启和停止 ufw防火墙
  10. 虚拟机VMware安装PhoenixOS(凤凰OS)