在项目开发中,有一部分依赖,并不是各个模块都共有的,可能只是其中的一小部分模块中使用到了这个依赖。可以使用Maven的版本锁定功能<dependencyManagement>。
<dependencyManagement> 是 Maven 项目对象模型(POM)中的一个重要元素,它的作用如下:
1.统一管理依赖版本:在父 POM 中定义依赖的版本号,子模块将继承这些配置。这样可以确保所有子模块使用相同的依赖版本,避免版本冲突。
2.声明依赖但不引入:在 <dependencyManagement> 中声明的依赖不会直接引入到 classpath 中,只有当子模块中具体引用了该依赖时才会被引入。
3.简化子模块配置:子模块只需要声明依赖的groupId和artifactId,不需要重复声明版本号等信息,简化了配置。
父pom:
<dependencyManagement> <dependencies> <!--JWT令牌--> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> </dependencies> </dependencyManagement>
子pom:
<dependencies>
<!--JWT令牌-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
</dependencies>
总结:
- 父工程:在
<dependencyManagement>
中定义依赖及其版本号,目的是统一管理所有子模块的依赖版本。 - 子工程:如果需要使用某个依赖,仍需在子模块的
<dependencies>
中显式声明该依赖,但无需指定版本号,因为版本号由父工程统一管理。 - 版本变更:如果需要更新依赖版本,只需在父工程的
<dependencyManagement>
中修改版本号,所有子模块会自动继承这一变更,无需逐个修改。