在Spring Boot中,配置应用程序的监听端口有多种方式。以下是常见的几种方法:
1. 通过 application.properties 或 application.yml 文件配置
application.properties
server.port=8081
application.yml
server:
port: 8081
如果没有显式配置 server.port,Spring Boot 默认使用 8080 端口。
2. 通过命令行参数配置
在运行Spring Boot应用时,可以通过命令行参数动态指定端口。
java -jar myapp.jar --server.port=8082
3. 通过编程方式配置
可以在主应用程序类中通过编程方式设置端口。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> factory.setPort(8084);
}
}