在本文中,您将学习如何在 Spring Boot 中更改默认端口。默认情况下,嵌入式 WEB 服务器使用 8080端口来启动 spring 引导应用程序。有几种方法可以更改该端口,如下所述。 使用配置文件更改端口 在 Spring Boot
在本文中,您将学习如何在 Spring Boot 中更改默认端口。默认情况下,嵌入式 WEB 服务器使用 8080端口
来启动 spring 引导应用程序。有几种方法可以更改该端口,如下所述。
在 Spring Boot 中更改默认端口的最简单、更快捷的方法是覆盖配置文件中的默认值。Spring 引导使用server.port
配置属性来指定端口。
以下示例演示如何在application.properties
文件中指定自定义端口:
server.port=8888
现在服务器将在8888
端口上启动应用程序。为application.yml
,您需要添加以下内容:
server: port: 8888
如果将上述文件放置在src/main/resources/
文件夹中,Spring Boot 会自动加载。
您还可以设置系统属性来更改 Spring 引导应用程序的默认端口。您需要做的就是在将启动服务器的操作系统上设置一个SERVER_PORT
环境变量。
对于基于 Unix 的操作系统,请键入以下命令以设置环境变量:
export SERVER_PORT=8888
对于Windows操作系统,您必须使用以下命令:
setx SERVER_PORT 8888
在 Spring 引导中更改默认端口的另一种方法是在启动应用程序时使用命令行参数。例如,如果要将应用程序打包并作为 jar 文件运行,则可以使用 Java 命令设置server.port
参数:
$ java -jar spring-boot-app.jar --server.port=8888
上述命令等效于以下内容:
$ java -jar -Dserver.port=8888 spring-boot-app.jar
您可以在启动应用程序或自定义嵌入式服务器配置时以编程方式更改默认端口。
若要在启动应用程序时在主应用程序类中设置端口,请使用以下代码:
@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication application = new SpringApplication(Application.class); application.setDefaultProperties(Collections.singletonMap("server.port", "8888")); application.run(args); }}
要自定义嵌入式服务器配置,您必须实现如下所示的WebServerFactoryCustomizer
接口:
@Componentpublic class PropertiesCustomizer implements WebServerFactoryCustomizer { @Override public void customize(ConfigurableWebServerFactory factory) { factory.setPort(8888); }}
如果应用程序部署在不同的环境中,则可能需要在不同的端口上运行它。
例如,您可能希望将 8888
用于开发,将 8889
用于 Spring 引导应用程序的生产环境。
为此,请在src/main/resources/
文件夹中创建一个名为application-dev.properties
开发环境的新文件,其中包含以下内容:
server.port=8888
接下来,使用不同的端口为生产环境创建一个application-prod.properties
文件:
server.port=8889
要激活所需的 Spring 引导配置文件,请将以下属性添加到该application.properties
文件中:
# spring boot active profile - div or prodspring.profiles.active=dev
就是这样。Spring 引导将自动为当前活动的配置文件选择服务器端口。
如果要在任何可用的随机端口上运行 Spring Boot 应用程序,只需设置server.port=0
属性即可。嵌入式 Web 服务器将使用操作系统本机查找可用端口,以防止冲突并将其分配给应用程序。
来源地址:https://blog.csdn.net/allway2/article/details/128210587
--结束END--
本文标题: 如何在 Spring Boot中更改默认端口
本文链接: https://www.lsjlt.com/news/393286.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-13
2024-05-13
2024-05-11
2024-05-11
2024-05-10
2024-05-07
2024-04-30
2024-04-30
2024-04-30
2024-04-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0