如何在 `mvn spring-boot:run` 时同时激活 `local,debug`?

解读

国内面试官问这条命令,核心想验证两点:

  1. 你是否真的在本地调过 Spring Boot,而不是只会“点 IDE 的绿色三角”;
  2. 你对 Maven 属性传递、Spring Boot 多环境机制、Profile 激活顺序的“坑点”是否熟。
    很多候选人直接甩 -Dspring.profiles.active=local,debug,结果现场连不上 MySQL 或日志级别没出来,就被追问“为什么没生效”,于是翻车。
    务必把 Maven 属性 -> Spring Boot 属性 -> Profile 激活这一条链路讲清,再给出“最稳写法”,才能拿到高分。

知识点

  1. spring-boot:run 插件目标
    由 spring-boot-maven-plugin 提供,跑在 Maven 的 run 生命周期,启动的是 fork 出的新 JVM,因此系统属性必须显式传进去。
  2. Profile 激活的 4 条主流路径
    a) application-{profile}.properties / application-{profile}.yml 存在即被识别;
    b) spring.profiles.active 系统属性;
    c) SPRING_PROFILES_ACTIVE 环境变量;
    d) maven 的 profiles 里通过 spring.profiles.active 变量注入。
    优先级 b > c > a,且支持逗号分隔多值。
  3. Maven 属性与 Spring 属性命名空间隔离
    -Dspring.profiles.active=xxx 是 JVM 系统属性,不是 Maven 属性,因此不需要在 POM 里做任何 <properties> 声明即可生效。
  4. 国内公司常见“坑”
    • 公司私服镜像把 spring-boot-maven-plugin 降版到 1.5.x,不支持多 Profile 逗号语法;
    • 同时用了 spring.profiles.include 和 spring.profiles.active,后者会覆盖前者,导致“缺配置”;
    • Windows PowerShell 把逗号当成数组分隔符,必须加引号。

答案

最简洁、可移植、国内各版本插件都验证过的写法:

mvn spring-boot:run -Dspring-boot.run.profiles=local,debug

解释:

  • spring-boot.run.profiles 是 spring-boot-maven-plugin 的 官方参数,从 2.0.0.RELEASE 开始提供,插件会把值直接塞进 fork 进程的 spring.profiles.active,比 -Dspring.profiles.active=xxx 更可靠;
  • 逗号分隔,顺序敏感,local 在前、debug 在后,符合 Spring Boot “后加载的覆盖先加载的” 规则;
  • 无需修改 POM,对 CI、同事电脑、云原生构建零侵入;
  • Windows 下任意终端、Linux/Mac 下 bash/zsh 均通过,避免引号转义问题。

若插件版本低于 2.0(老项目),退化成:

mvn spring-boot:run -Dspring.profiles.active=local,debug

注意:此时必须确认 <fork>true</fork>,否则属性传不到子进程。

拓展思考

  1. 持续集成场景
    在 GitLab-CI 或 Jenkinsfile 里,不要把 Profile 写死,而是用 mvn spring-boot:run -Dspring-boot.run.profiles=${ACTIVE_PROFILES},把 ACTIVE_PROFILES 作为变量注入,实现“同一套代码,同一行命令,多套环境”,这是国内大厂蓝绿发布、特性灰度的标配玩法。
  2. 本地一键脚本
    给团队写一个 run.sh/run.bat,内容:
    #!/bin/bash
    PROFILES=${1:-local,debug}
    mvn spring-boot:run -Dspring-boot.run.profiles=$PROFILES
    
    新人入职只需 ./run.sh 即可,避免每个人自己拼命令,减少“为什么我这端口占用”这类低级 support。
  3. 与 Docker 结合
    多阶段构建时,Maven 构建阶段用 -Dspring-boot.run.profiles=docker 打可执行 jar,Runtime 阶段再通过 ENV SPRING_PROFILES_ACTIVE=prod,perf 覆盖,实现“构建无环境,运行指定环境”,符合国内金融、政企对“不可变制品”的审计要求。