首页 / Spring Boot 入门教程 / 端口与 Context Path

Spring Boot 入门教程

端口与 Context Path

本教程共 48 篇 · 第 15 篇 · 更新于 2026-08-13 · 约 4 分钟阅读

server.portcontext-path端口配置随机端口WebServerFactoryCustomizerTomcat

本节目标:掌握端口和访问路径前缀的配置方法,覆盖配置文件、命令行、环境变量、随机端口与运行时获取。

默认值先记住

内嵌 Tomcat 默认监听 8080 端口,访问根路径是 /

mvn spring-boot:run

启动后访问 http://localhost:8080/ 就能看到应用。

端口冲突是新手第一坑。8080 被别的程序占了,启动就报错。

配置文件改端口

最直接的方式,application.yml 里写:

server:
  port: 8081

properties 写法等价:

server.port=8081

改完重启,访问 http://localhost:8081/

命令行与系统属性

不打包也能覆盖:

mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8082"

打包后:

java -jar hello-app.jar --server.port=8082

系统属性写法(注意要在 -jar 前面):

java -Dserver.port=8082 -jar hello-app.jar

环境变量写法:

SERVER_PORT=8082 java -jar hello-app.jar
Note

四种方式优先级:命令行参数 > 系统属性 > 环境变量 > 配置文件。第 12 章的优先级表在这里照样适用。

不同环境不同端口

配合 Profile,每个环境一个端口:

# application-dev.yml
server:
  port: 8081
# application-prod.yml
server:
  port: 443
java -jar hello-app.jar --spring.profiles.active=prod

公共的 application.yml 只写默认值,环境文件负责覆盖。

随机端口

不想固定端口?写成 0,让系统自动分配:

server:
  port: 0

启动日志里能看到实际端口:

Tomcat started on port 54871 (http) with context path '/'

测试场景常用这招,避免端口冲突。

随机端口在测试里的标准用法

集成测试配随机端口,是最常见的组合:

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WebTests {

    @LocalServerPort
    private int port;

    @org.junit.jupiter.api.Test
    void portShouldBeAssigned() {
        System.out.println("测试用端口: " + port);
    }
}

RANDOM_PORT 让测试用随机端口跑,@LocalServerPort 注入实际值。

多个测试并行时互不干扰,这是官方推荐姿势。

绑定网卡地址

服务器有多块网卡时,用 server.address 指定监听地址:

server:
  address: 127.0.0.1

只允许本机访问。写成 0.0.0.0:: 则监听所有网卡。

Warning

生产环境别把服务裸绑到公网地址。要么走反向代理,要么配防火墙。

超时与 HTTPS 配置

连接超时也有对应键:

server:
  port: 8443
  tomcat:
    connection-timeout: 5000

HTTPS 证书配置预览:

server:
  port: 8443
  ssl:
    enabled: true
    certificate: classpath:cert.pem
    certificate-private-key: classpath:key.pem

4.x 里证书用 PEM 文件即可,不用再转 PKCS12。

Note

SSL 的细节在后续 HTTPS 相关章节展开。这里先知道键在哪,遇到需求知道去哪查。

响应式应用的区别

WebFlux 项目没有 Servlet 容器,但端口键和 MVC 一样,仍是 server.port

server:
  port: 8080

区别在路径前缀:server.servlet.context-path 在 WebFlux 下无效,要写 spring.webflux.base-path

选错键不报错,但配置不生效。先确认项目是 MVC 还是 WebFlux。

运行时获取真实端口

随机端口下,代码里怎么知道端口号?监听事件:

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class PortReporter implements ApplicationListener<WebServerInitializedEvent> {

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        int port = event.getWebServer().getPort();
        System.out.println("实际端口是:" + port);
    }
}

还有一种写法:${local.server.port} 占位符。但它只在属性被解析时可用,场景有限,事件监听更可靠。

Context Path 是什么

Context Path 是 URL 的前缀路径。

默认是空,访问 http://localhost:8080/hello

设成 /myapp 后,得访问 http://localhost:8080/myapp/hello

多应用共用一台服务器、一个端口时,用前缀区分。

配置 Context Path

配置文件:

server:
  servlet:
    context-path: /myapp

properties 等价写法:

server.servlet.context-path=/myapp

命令行:

java -jar hello-app.jar --server.servlet.context-path=/myapp

环境变量:

SERVER_SERVLETCONTEXTPATH=/myapp java -jar hello-app.jar
Warning

路径必须以 / 开头。写 myapp 不生效,Spring Boot 会直接忽略或报错。
另外注意这是 Servlet 应用的键。响应式 WebFlux 应用用 spring.webflux.base-path,别搞混。

Note

版本对照:Spring Boot 1.x 时代这个键叫 server.context-path,2.x 起改为 server.servlet.context-path。4.x 沿用的仍是后者。

编程式配置

不想依赖配置文件?用 WebServerFactoryCustomizer:

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.server.servlet.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServerConfig {

    @Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> serverCustomizer() {
        return factory -> {
            factory.setPort(9090);
            factory.setContextPath("/myapp");
        };
    }
}

适合端口从注册中心、数据库等动态读取的场景。

Tip

编程式配置的优先级高于配置文件。两处都写了,以代码为准。

端口冲突怎么办

启动报 Port 8080 was already in use,三步处理:

  • netstat -ano | findstr 8080 找占用进程(Windows)。
  • taskkill /PID <进程号> /F 结束它(确认不是重要服务)。
  • 或者干脆换个端口。

开发机 8080 经常被占,直接改用 8081 最省心。

小结

  • 默认端口 8080,server.port 一键修改。
  • 命令行、系统属性、环境变量都能覆盖配置文件。
  • server.port=0 拿随机端口,测试用 RANDOM_PORT + @LocalServerPort。
  • server.servlet.context-path 设置 URL 前缀。
  • server.address 绑网卡,server.ssl.* 配 HTTPS。
  • WebFlux 端口键与 MVC 相同,路径前缀用 spring.webflux.base-path
  • 动态场景用 WebServerFactoryCustomizer 编程式配置。