springboot分环境打包(maven动态选择环境)

时间:2022-01-18 10:54:25

分环境打包核心点:spring.profiles.active

pom.xml中添加:

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <logback.loglevel>DEBUG</logback.loglevel>
            <spring.profiles.active>dev</spring.profiles.active>
            <profileActive>dev</profileActive>
        </properties>
    </profile>
    <profile>
        <id>test</id>
        <properties>
            <logback.loglevel>INFO</logback.loglevel>
            <spring.profiles.active>test</spring.profiles.active>
            <profileActive>test</profileActive>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <logback.loglevel>INFO</logback.loglevel>
            <spring.profiles.active>prod</spring.profiles.active>
            <profileActive>prod</profileActive>
        </properties>
    </profile>
</profiles>

  

resources目录下的配置文件:

springboot分环境打包(maven动态选择环境)

其中,向application.yml文件中添加:

spring:
  profiles:
    active: @profileActive@

完成后,看看pom.xml文件中是有build模块(一般创建springboot项目会在pom.xml文件下自动生成),如果没有添加:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

然后再Terminal控制台输入maven打包命令:

  1. 选择dev环境(默认):
mvn clean package
  1. 选择test环境:
mvn clean package -P test
  1. 选择prod环境:
mvn clean package -P prod