返回
告别默认8080:教你轻松配置Spring Boot端口
java
2024-03-08 19:41:51
为 Spring Boot 应用配置端口:告别 8080
简介
Spring Boot 是一个流行的 Java 框架,让开发基于 Spring 的应用程序变得轻而易举。默认情况下,Spring Boot 应用在端口 8080 上运行,但有时我们需要定制端口以满足特定需求。本博客将深入探讨如何轻松配置 Spring Boot 应用的端口。
方法
1. application.properties
application.properties 文件是 Spring Boot 应用的配置属性文件。编辑此文件,添加以下属性:
server.port=你的端口号
2. Spring Boot CLI
Spring Boot CLI(命令行界面)提供了另一种便利的方法。运行以下命令:
spring.io init --port=你的端口号
3. Spring Boot 注解
也可以使用 @SpringBootApplication
注解来配置端口:
@SpringBootApplication
@EnableAutoConfiguration
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return (container) -> container.setPort(你的端口号);
}
}
代码示例
application.properties
# application.properties
server.port=9000
Spring Boot CLI
$ spring.io init --port=9000
# application.properties
server.port=9000
Spring Boot 注解
@SpringBootApplication
@EnableAutoConfiguration
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return (container) -> container.setPort(9000);
}
}
常见问题
如何检查端口配置是否正确?
启动应用程序,并使用 netstat
命令检查监听的端口:
$ netstat -antp | grep 9000
如何在部署后更改端口?
可以在服务器配置中修改端口,或使用反向代理在部署后更改应用程序的端口。
结论
配置 Spring Boot 应用的端口是一项简单的任务,可以满足不同的需求。通过遵循本文中介绍的方法,你可以轻松地将应用程序配置为使用特定的端口。现在,你的 Spring Boot 应用可以告别默认的 8080 端口,自由驰骋在指定的港湾中。