maven多module项目的依赖管理

前言

这里主要说两种情况:

  1. 子module依赖父module
  2. 子module依赖子module

子module依赖父module

子module依赖父module又分为两种情况: dependencies 和 dependencyManagement

两种情况下子module都要在<parent>标签中依赖父module

dependencies

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

子项目会从父项目中继承dependencies中的所有依赖,即使在子项目中没有引入。

dependencyManagement

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.3.4.RELEASE</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

注意需要在父项目中指定版本,并且需要在子项目中显式的引用。

子项目pom:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

如果子项目中没有指定版本,则按照父项目中指定的版本引入;如果子项目中指定了版本,则按照子项目中指定的版本引入。

子module依赖子module

假设B模块依赖A模块,则只需要在B的pom中引入A即可,不过需要注意一点,如果在A模块中引入了spring-boot-maven-plugin插件,则需要一点特殊的配置:

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <classifier>exec</classifier>
                </configuration>
            </plugin>
        </plugins>
    </build>

需要<configuration>中的配置的原因是:

默认情况下,maven会先打一个普通的jar包,然后如果引入了该插件,则该插件会将普通的jar包重命名为a.jar.original, 然后重新打一个可执行的jar包,命名为a.jar,但是可执行的jar包被依赖的话是会报错的。

为什么依赖可执行的jar包会报错?
我大致解压了一下两个jar包,其实里面的class的路径是不一样的。

posted on 2020-10-10 12:05  斜月三星一太阳  阅读(1050)  评论(0编辑  收藏  举报