Maven利用profile根据环境引用相应jar包

引言

在开发中遇到这样的情况:某些jar包只需要在开发环境使用,其它环境不使用,比如Swagger包。这时候就需要我们根据不同环境打包不同的jar包。

方法

查阅了Maven的文档,发现使用Maven打包的时候可以利用profile配置区分环境。

解决

在pom.xml加入profile配置

<profiles>
    <profile>
        <id>dev</id>
        <dependencies>
            <dependency>
                <groupId>com.moda</groupId>
                <artifactId>moda-swagger-spring-boot-starter</artifactId>
            </dependency>
        </dependencies>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
</profiles>

打包的使用命令

 mvn clean package -P dev

由于activeByDefault指定为默认,也可以不加 -P dev效果是一样

 mvn clean package

其它环境,注意在dev前面加入“!”,表示禁止id=dev的配置

 mvn clean package -P !dev

总结

通过profile可以指定多个环境,比如dev、test、uat、prod,每个环境可以定制化的配置,达到在不改动代码的情况下可以很方便的切换环境。

资料

Introduction to the POM

在Java Maven项目中,如果需要引入两个不同版本的同一个依赖库,通常是为了处理兼容性问题或者是某个阶段特定的需求。Maven通过`<dependencyManagement>`和`<dependencies>`标签来管理这种场景: 1. **使用dependencyManagement**: 在pom.xml文件的`<dependencyManagement>`部分,可以声明一个父POM(parent POM),它定义了不同模块共用的依赖版本。然后在每个子模块的`<dependencies>`部分,你可以引用这个父POM,并针对个别情况使用`<version>`属性指定特定版本。 ```xml <dependencyManagement> <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>library</artifactId> <version>1.0.0</version> <!-- 共享的基础版本 --> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>library</artifactId> <version>1.1.0</version> <!-- 特定模块使用的更新版本 --> </dependency> </dependencies> ``` 2. **使用 profiles**: 如果你想基于构建环境或者条件动态选择不同版本,可以利用Mavenprofiles功能。创建不同的profile,在每个profile下配置不同的依赖版本。 ```xml <profiles> <profile> <id>dev</id> <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>library</artifactId> <version>1.0.0</version> </dependency> </dependencies> </profile> <profile> <id>prod</id> <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>library</artifactId> <version>1.1.0</version> </dependency> </dependencies> </profile> </profiles> <build> <profiles> <activeProfile>dev</activeProfile> <!-- 或者 prod,取决于当前激活的profile --> </profiles> </build> ``` 切换profile时,对应的依赖版本就会生效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值