Spring boot 多文件配置

210 阅读1分钟

作用

  1. 开发、发布过程中,需要切换多种环境(如数据库链接,端口号等)
  2. 网上搜索了,结果搜到很多辣鸡文章,漏了关键信息配不成功,所以写下亲测可用的过程,避免后面的老铁被耽误
  3. 最后终于找到了一篇正确的,不过内容不精练,重新整理获得,大家也可以直接看原文章:

blog.csdn.net/xiaochouyu_…

主要步骤

  1. 在pom.xml添加配置
  2. 在resources添加对应环境的配置文件
  3. 运行指定配置

环境

idea2020
spring-boot 2.3.1RELEASE JDK 14.0.2

详细步骤

1.在pom.xml中添加配置

添加环境

<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <environment>dev</environment>  <!-- 环境名,可以任意名字,在资源配置中使用 ${environment}就能获取值 -->
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>  <!-- 默认环境,当使用mvn启动不指定配置时,默认使用这个环境 -->
        </activation>
    </profile>
    <profile>
        <id>beta</id>
        <properties>
            <environment>beta</environment>  <!-- beta环境 -->
        </properties>
    </profile>
</profiles>

添加资源配置

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>application.properties  </include><!-- 原配置文件 -->
                <include>application-${environment}.properties</include>  <!-- 带环境的配置文件,注意使用"-"连接,否则无法生效 -->
                <include>**/*.xml</include>  <!-- 其他资源文件,不填写会导致程序运行时找不到文件 -->
                <include>**/*.sql</include>  <!-- 其他资源文件,不填写会导致程序运行时找不到文件 -->
            </includes>
            <filtering>true</filtering>  <!-- 过滤,不知道啥效果,有兴趣的可以自己修改测试下 -->
        </resource>
    </resources>
</build>

此时在Maven窗口会看到配置选项

添加配置文件

添加application-dev.properties
添加application-beta.properties
两个文件名对应pom.xml中的 application-${environment}.properties

环境配置文件是在原配置上叠加覆盖的

# 如application.properties中
server.port=8080

# 如application-dev.properties中
server.port=8081
spring.datasource.username=dev

# 如application-beta.properties中
server.port=8082
spring.datasource.username=beta

结果dev环境中:port=8081,username=dev
beta环境中:port=8082,username=beta

使用配置

启动的命令后加上 -P 配置名称

mvnw clean spring-boot:run          # 使用默认配置(此例子中是dev)
mvnw clean spring-boot:run -P beta  # 使用beta环境
mvnw clean spring-boot:run -P dev   # 使用dev环境

mvnw clean package                  # 使用默认配置(此例子中是dev)
mvnw clean package -P beta          # 使用beta环境
mvnw clean package -P dev           # 使用dev环境

查看结果

很明显可以观察到,指定不同环境启动时,端口号是对应的配置文件上的