Maven 父子项目依赖问题

2,007 阅读1分钟

1,Parent项目pom.xml中dependencyManagement和dependencies区别

1,<dependencyManagement>里只是声明依赖,并不实现引入。
   因此子项目还需要显示声明需要的依赖,如果不在子项目中声明依赖,是不会从父项目中继承下来的;
   只有在子项目中写了该依赖项,并且没有指定具体版本,才会从父项目中继承该项。
   并且version和scope都读取自父pom;另外如果子项目中指定了版本号,那么会使用子项目中指定的jar版本
2,<dependencies>实现了引入依赖的jar,注意这里说的<dependencies>并不是<dependencyManagement>标签下的<dependencies>
   子项目默认会依赖父项目中所有声明的<dependencies>

2,如果子项目是jar项目,依赖了大量parent的pom.xml中的jar依赖,那么打包的时候会打到子项目这个jar中吗?

默认是不打进去的,做了个试验,heimen-common项目继承parent的pom.xml

<parent>
   <artifactId>heimen</artifactId>
   <groupId>com.heimen.cn</groupId>
   <version>1.0-SNAPSHOT</version>
</parent>
  • 正常打包后 这样的是对的,如果打包的jar是一个启动项目,那么只需要把相关的依赖放在一个文件夹中,然后这个jar去依赖就行。
  • 那可以把jar所从parent项目pom.xml中依赖的jar来打包到当前jar中吗?答案是可以的,需要在当前子项目的pom.xml中配置以下插件
<plugins>
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
        <executions>
            <execution>
                <id>make-assembly</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>

重新打包

关于Jar的依赖管理dependencyManagement和插件管理pluginManagement都不会引入Jar或plugin,都是定义和声明,都是为了统一多项目的依赖版本