10 强制约束依赖的版本号

1 强制约束版本号

  • 项目结构如下,所有项目都依赖mall-common


    项目结构
  • mall-common中依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
</dependency>
  • mall-order中依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.1.58</version>
</dependency>
  • mall-order依赖结构如下
mall-order ->
    mall-common ->
        fastjson-1.2.58

mall-order ->
    fastjson-1.1.58
  • 此时就近原则生效,mall-order.jar中只存在fastjson-1.1.58,XXX Not Found问题

2 如何强制约束版本号

  • 针对mall-common,开发一个pom包(mall-common-bom),该pom包专门用dependencyManagement来约束依赖方的各个版本号
  • 依赖方(mall-order)不直接依赖mall-common,而是依赖于mall-common-bom,此时mall-order在dependency声明fastjson依赖时,在对fastjson自定义依赖版本时,pom就会报错

3 项目使用

mall-common
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
</dependency>
---------------------------------------------------------------------------------------------------------
mall-common-bom
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.mall.common</groupId>
            <artifactId>mall-common</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
    </dependencies>
</dependencyManagement>

---------------------------------------------------------------------------------------------------------
mall-order
<dependencyManagement>
   <dependencies>
       <dependency>
           <groupId>com.mall.common</groupId>
           <artifactId>mall-common-bom</artifactId>
           <version>1.0.0</version>
           <type>pom</type>
           <scope>import</scope>
       </dependency>
   </dependencies>
</dependencyManagement>

<!-- 此时如果声明fastjson的依赖版本号,pom文件报错-->
 <dependencies>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.1.58</version>
    </dependency>
</dependencies>

推荐阅读更多精彩内容