(给ImportNew加星标,提高Java技能)
转自:data4
链接:www.jianshu.com/p/f6ca45865025
管理包依赖是 Maven 核心功能之一,下面通过如何引入 jar 包;如何解析 jar 包依赖;包冲突是如何产生;如何解决包冲突;依赖管理解决什么问题;什么是依赖范围;使用包依赖的最佳实践等 6 个问题来介绍。
<dependencies><!-- https://mvnrepository.com/artifact/org.apache.hadoop/zookeeper --><dependency><groupId>org.apache.hadoop</groupId><artifactId>zookeeper</artifactId><version>3.3.1</version></dependency></dependencies>
<dependency><groupId>org.apache.hadoop</groupId><artifactId>zookeeper</artifactId><version>3.3.1</version><exclusions><exclusion><groupId>jline</groupId><artifactId>jline</artifactId></exclusion></exclusions></dependency>
mvn dependency:helpmvn dependency:analyzemvn dependency:treemvn dependency:tree -Dverbose依赖管理解决什么问题
<project>...<dependencies><dependency><groupId>group-a</groupId><artifactId>artifact-a</artifactId><version>1.0</version><exclusions><exclusion><groupId>group-c</groupId><artifactId>excluded-artifact</artifactId></exclusion></exclusions></dependency><dependency><groupId>group-a</groupId><artifactId>artifact-b</artifactId><version>1.0</version><type>bar</type><scope>runtime</scope></dependency></dependencies></project>projectB:
<project>...<dependencies><dependency><groupId>group-c</groupId><artifactId>artifact-b</artifactId><version>1.0</version><type>war</type><scope>runtime</scope></dependency><dependency><groupId>group-a</groupId><artifactId>artifact-b</artifactId><version>1.0</version><type>bar</type><scope>runtime</scope></dependency></dependencies></project>
<project>...<dependencyManagement><dependencies><dependency><groupId>group-a</groupId><artifactId>artifact-b</artifactId><version>1.0</version><type>bar</type><scope>runtime</scope></dependency></dependencies></dependencyManagement></project>则 projectA 和 projectB 均不需要指定 group-a/artifact-b 的 version 信息。 未来升级 version 信息时,只需要在 parent 内部指定。 projectA:
<project>...<dependencies><dependency><groupId>group-a</groupId><artifactId>artifact-a</artifactId><version>1.0</version><exclusions><exclusion><groupId>group-c</groupId><artifactId>excluded-artifact</artifactId></exclusion></exclusions></dependency><dependency><groupId>group-a</groupId><artifactId>artifact-b</artifactId></dependency></dependencies></project>projectB:
<project>...<dependencies><dependency><groupId>group-c</groupId><artifactId>artifact-b</artifactId><version>1.0</version><type>war</type><scope>runtime</scope></dependency><dependency><groupId>group-a</groupId><artifactId>artifact-b</artifactId></dependency></dependencies></project>依赖范围
项目中源代码使用的 jar 包一定在 pom.xml 中显示引用。
经常 check 一下包冲突,检查是否需要处理。
当使用多个模块时,parent 一定要使用包管理模块来规范 Jar 包版本,而不是包依赖模块直接引入依赖。dependencyManagement vs dependencies
看完本文有收获?请转发分享给更多人
关注「ImportNew」,提升Java技能
好文章,我在看❤️