Spring Boot 2.7.3应用如何部署到不同端口?
问题
我已经实现了基于Spring Boot 2.7.3版本的应用,现在希望将其部署到不同端口。我尝试使用Spring Boot 1.x中的Maven构建目标spring-boot:run -Dserver.port=7878,但应用仍仅部署在application.properties中定义的默认端口或8080。请问Spring Boot 2.7.3中是否有其他属性/构建目标可实现多端口部署?我了解到Spring Boot 2.x+中run已重命名为spring-boot.run,run.profiles已重命名为spring-boot.run.profiles。
解决方案
你遇到的问题是因为Spring Boot 2.x+的Maven插件调整了参数传递逻辑,直接用-Dserver.port会把参数传给Maven进程而非Spring Boot应用进程,导致应用读取不到该配置。以下是几种可行的实现方式:
1. 通过JVM参数传递端口
使用spring-boot.run.jvmArguments将端口参数传递给Spring Boot的JVM进程,命令如下:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=7878"
2. 通过应用启动参数传递端口
利用spring-boot.run.arguments直接传递命令行参数给Spring Boot,效果和启动jar包时添加--server.port一致:
mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=7878"
3. 打包后启动多端口实例
如果需要同时运行多个不同端口的应用实例,先打包成jar包,再分别启动不同进程:
# 先打包应用 mvn clean package # 启动第一个实例(端口7878) java -jar target/你的应用包名.jar --server.port=7878 # 启动第二个实例(端口7879) java -jar target/你的应用包名.jar --server.port=7879
4. 通过Profile配置多端口
创建对应不同端口的环境配置文件,用Profile实现切换:
- 在
application.properties中设置默认激活的Profile(可选):spring.profiles.active=dev - 创建
application-dev.properties:server.port=7878 - 创建
application-test.properties:server.port=7879
然后通过Maven指定Profile启动:
mvn spring-boot:run -Dspring-boot.run.profiles=dev mvn spring-boot:run -Dspring-boot.run.profiles=test
内容的提问来源于stack exchange,提问作者Hari Prasad
相关产品推荐
相关产品推荐

