今天创建了一个多模块的工程,在父模块中已经添加了依赖,但是在子模块中的代码里还是依旧提示缺少依赖。
仔细一下,是把依赖写在了 <dependencyManagement>
节点下。
这里我就感到很疑惑,dependencyManagement
?
<dependencies>
相对于 <dependencyManagement>
,所有声明在<dependencies>
里的依赖都会自动引入,并默认被所有的子项目继承。
<dependencyManagement>
<dependencyManagement>
里只是声明依赖,并不实现引入。
因此子项目需要显示的声明需要用的依赖。如果不在子项目中声明依赖,是不会从父项目中继承下来的;只有在子项目中写了该依赖项,并且没有指定具体版本,才会从父项目中继承该项,并且version和scope都读取自父pom;另外如果子项目中指定了版本号,那么会使用子项目中指定的jar版本。
Itoo-base-parent(pom.xml)
<dependencyManagement> <dependencies> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> <version>${org.eclipse.persistence.jpa.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>${javaee-api.version}</version> </dependency> </dependencies> </dependencyManagement>
Itoo-base(pom.xml)
<!--继承父类-->
<parent> <artifactId>itoo-base-parent</artifactId> <groupId>com.tgb</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../itoo-base-parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>itoo-base</artifactId> <packaging>ejb</packaging> <!--依赖关系--> <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> <scope>provided</scope> </dependency> </dependencies>
</project>
这样做的好处:统一管理项目的版本号,确保应用的各个项目的依赖和版本一致,才能保证测试的和发布的是相同的成果,因此,在顶层pom中定义共同的依赖关系。
同时可以避免在每个使用的子项目中都声明一个版本号,这样想升级或者切换到另一个版本时,只需要在父类容器里更新,不需要任何一个子项目的修改;如果某个子项目需要另外一个版本号时,只需要在dependencies中声明一个版本号即可。子类就会使用子类声明的版本号,不继承于父类版本号。