maven-maven使用-P参数打包不同环境问题
maven-maven使用-P参数打包不同环境
一般的,开发环境有dev, test 和 pro,他们的配置多有不同,那么就可以使用 maven -P这个参数进行多环境打包
如 clean install -Dmaven.test.skip=true -P pro,就可以切换成生产环境,和 jenkins 配合简直不要太爽!!
举个例子
以 boot 项目来说,现有目录结构:
/src
/main
/java
/resources
/static
/templates
application.yml
application-dev.yml
application-pro.yml
application-test.yml
application.yml:
server:
port: 8080
spring:
profiles:
# @spring.profiles.active@ 变量将会随着参数的传入被替换
active: @spring.profiles.active@
然后三个不同环境的配置文件分别为:
application-dev.yml:
server:
port: 8080
spring:
application:
name: mpp-dev
application-pro.yml:
server:
port: 8081
spring:
application:
name: mpp-pro
application-test.yml:
server:
port: 8082
spring:
application:
name: mpp-test
配置 maven 的 pom 文件,默认激活 dev 环境:
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>
<profile>
<id>test</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<spring.profiles.active>test</spring.profiles.active>
</properties>
</profile>
<profile>
<id>pro</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
//spring.profiles.active即在application.yml文件中
//定义的参数@spring.profiles.active@
<spring.profiles.active>pro</spring.profiles.active>
</properties>
</profile>
</profiles>
根据环境过滤只有当前环境的配置文件:
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 替换占位符-->
<filtering>true</filtering>
<excludes>
<exclude>application-*.yml</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<!-- 替换占位符-->
<filtering>true</filtering>
<includes>
<include>application-${spring.profiles.active}.yml</include>
</includes>
</resource>
</resources>
需要加入 plugin 为:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
</plugin>
测试
在当前项目 pom 文件所在的目录下打开命令行,输入 clean package -Dmaven.test.skip=true -P pro
可以看到:
/target
/classes
/com
application.yml
application-pro.yml
打开 application.yml 文件:
server:
port: 8080
spring:
profiles:
active: pro
可以发现之前 @spring.profiles.active@ 变量已经被替换成了 pro ,而且配置文件只关于生产环境,而且dev 和 test 的配置文件都已经被过滤了
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
MyBatis 中 type-aliases-package的作用(简化类型映射)
MyBatis中type-aliases-package的作用是简化类型映射,通过指定包路径,MyBatis会自动扫描该包下的所有类并为这些类生成类型别名,减少XML配置文件中的冗长代码,感兴趣的朋友跟随小编一起看看吧2024-11-11
Spring Boot应用程序同时支持HTTP和HTTPS协议的实现方法
如今,企业级应用程序的常见场景是同时支持HTTP和HTTPS两种协议,这篇文章考虑如何让Spring Boot应用程序同时支持HTTP和HTTPS两种协议,需要的朋友可以参考下2019-10-10
JAVA基础类库之String类,StringBuffer类和StringBuilder类
这篇文章主要介绍了Java中基础类库的String类,StringBuffer类和StringBuilder类,是Java入门学习中的基础知识,需要的朋友可以参考下2021-09-09


最新评论