场景

在小型项目中,需要配置不同环境的配置文件。在spring boot中直接提供了运行参数的方式。




springBoot教程:3.多环境配置文件_spring boot


image.png


如图,如果想加载application-prod.properties的在运行的加上参数​​--spring.profiles.active=prod​​​。
整体的命令是

java -jar  xxx.jar --spring.profiles.active=prod # 加载application-prod.properties

但缺点就是会将所有的配置文件都打包进jar文件。如果生产环境比较敏感,那么一些账户密码就泄露了。

因此可以采用maven的方式进行打包。

<!-- 分环境打包配置文件 -->
<profiles>
<!-- 本地环境 -->
<profile>
<id>local</id>
<build>
<resources>
<resource>
<directory>src/main/resources/local</directory>
</resource>
</resources>
</build>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>

<!-- 开发环境 -->
<profile>
<id>dev</id>
<build>
<resources>
<resource>
<directory>src/main/resources/dev</directory>
</resource>
</resources>
</build>
</profile>

<!--测试环境-->
<profile>
<id>tests</id>
<build>
<resources>
<resource>
<directory>src/main/resources/tests</directory>
</resource>
</resources>
</build>
</profile>

<!--线上环境-->
<profile>
<id>prod</id>
<build>
<resources>
<resource>
<directory>src/main/resources/prod</directory>
</resource>
</resources>
</build>
</profile>
</profiles>


<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>tests/**</exclude>
<exclude>prod/**</exclude>
<exclude>dev/**</exclude>
<exclude>local/**</exclude>
</excludes>
<filtering>true</filtering>
</resource>
</resources>


<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

使用命令​​mvn clean package -Dmaven.test.skip=true -Pprod​​即可。