Maven學習(3)-依賴管理-POM文件中依賴的版本鎖定詳解


pom.xml中依賴的定義樣例:

<dependencies>
  <dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>2.1.1</version>
  </dependency>
</dependencies>

但是,實際使用中,會發現pom.xml中很多依賴是沒有指定<version>的,如:

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

為什么呢?這就涉及到Maven中依賴的版本鎖定。

 

實際項目開發中,一個項目包含很多模塊,不同模塊有不同的依賴,也有多個模塊存在共同的依賴。如:

 

希望一個項目中,不同模塊使用的同一依賴采用相同的版本。可以:

(1)方式一:在每個模塊的pom.xml文件中指定依賴版本,人為確保不同模塊的pom.xml中相同依賴版本號一致。這樣會導致維護復雜,后續如果變更依賴版本,需要每個模塊排查修改。

(2)方式二:把所有的模塊的依賴,都在根目錄的pom.xml定義,然后被所有子模塊引用。這樣會導致子模塊引用冗余,對於子模塊不需要的依賴,也會被引用過來。

(3)方式三:maven提供了更好的方式,即maven依賴的版本鎖定:

         整個項目,在根pom.xml中通過<dependencyManagement>標簽定義依賴的版本: 

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>org.eclipse.persistence</groupId>
          <artifactId>org.eclipse.persistence.jpa</artifactId>
          <version>1.3</version>
        </dependency>
        <dependency>
          <groupId>javax</groupId>
          <artifactId>javaee-api</artifactId>
          <version>2.1.1</version>
        </dependency>
      </dependencies>
    </dependencyManagement>

         根目錄的pom.xml作為每個模塊pom.xml的父pom(通過在pom.xml文件中用<parent>指定),在模塊的pom.xml僅指定依賴,不指定版本即可:

          <dependencies> 
      <dependency> 
        <groupId>org.eclipse.persistence</groupId> 
        <artifactId>org.eclipse.persistence.jpa</artifactId> 
      </dependency> 
      <dependency> 
        <groupId>javax</groupId> 
        <artifactId>javaee-api</artifactId> 
      </dependency> 
    </dependencies> 

        實際上,maven在解析子模塊的pom.xml文件中依賴時,采用的就是父pom中<dependencyManagement>標簽定義的版本。

        <dependencyManagement>和<dependencies>的區別:

      (1)<dependencyManagement>用於定義依賴版本,並不是真實的依賴,所以maven在解析pom.xml文件時並不會把<dependencyManagement>內的內容作為真實依賴來做查找更新動作。

      (2)<dependencies>是真實的依賴,maven在解析pom.xml時,需要進行查找更新。

 

通過IDEA等創建的項目,項目根pom.xml中也存在沒有版本號的依賴,其版本號如何確定呢?

原因是:Maven為所有項目提供了公共的父pom,在項目的根pom.xml文件中通過<parent>引用。項目根pom.xml中也存在沒有版本號的依賴,集成的是Maven父pom中通過依賴版本管理定義的版本。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM