如何避免Maven本地测试Profile中重复引入H2依赖?
避免重复引入H2依赖的方案
方案一:使用dependencyManagement统一管理依赖坐标
在POM中添加dependencyManagement节点,统一定义H2依赖的基础坐标(包括版本),后续在全局依赖和Profile中引用时,无需重复编写groupId、artifactId和version,只需要指定不同的scope即可:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> ... <dependencyManagement> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>你的H2版本号</version> <!-- 例如2.2.224 --> </dependency> </dependencies> </dependencyManagement> <dependencies> ... <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency> </dependencies> <profiles> <profile> <id>local</id> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> </profile> </profiles> </project>
这种方式不仅减少了重复代码,后续修改H2版本时也只需要在dependencyManagement中操作一次,无需多处同步修改。
方案二:通过Profile覆盖依赖范围
如果不需要统一管理版本,也可以利用Maven的依赖优先级特性,仅在全局依赖中保留完整声明,Profile里只声明需要修改的scope:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> ... <dependencies> ... <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>你的H2版本号</version> <scope>test</scope> </dependency> </dependencies> <profiles> <profile> <id>local</id> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> </profile> </profiles> </project>
激活local Profile时,Maven会自动用Profile中声明的runtime scope覆盖全局的test scope,无需重复编写版本信息。
内容的提问来源于stack exchange,提问作者JGleason
相关产品推荐
相关产品推荐

