使用變量進行管理
定義一個版本號的變量
<properties>
<spring-framework-version>4.3.7.REALEASE</spring-framework-version>
</properties>
所有spring的jar版本都使用變量來定義版本:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework-version}</version>
<scope>test</scope>
</dependency>
使用maven的dependencyManagement管理
單個jar的管理
<dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
</dependencyManagement>
在引用依賴時,不需要填寫版本。
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
在一個項目中,這樣做的必要性不大,這種機制一般用於maven項目繼承,子項目可以直接使用簡化的依賴配置,從而確保和父項目版本一致。
這裏有一個問題,如果我們配置了:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
<scope>test</scope>
</dependency>
會發現依賴樹中,spring-test是4.3.7,而spring-data-jpa中依賴的其他spring子項目確實4.2.8,這經常會導致一些莫名其妙的問題,比如spring-test異常等等。
這個問題在使用下面的pom來管理時就可以避免了,針對spring-data-jpa項目尤其要注意。
pom管理jar集合的版本
以Spring爲例,它包含大量的子項目,爲了保持不同子項目的版本一致,官方提供了一個pom專門來管理版本。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.7.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
那麼大部分一級項目,都可以直接如下引用依賴了。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
之所以說大部分,如spring-data下面的子項目是Spring子項目中的一個子集。它提供了自己的pom包。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Hopper-SR4</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
它的版本不同於普通的版本號,如1.11.7.RELEASE這種,而是獨立的版本體系,具體版本參見:https://github.com/spring-projects/spring-data-commons/wiki/Release-planning
這個字符串的版本號,實際上又對應了真實的版本號,如:
Hopper-SR4 <-> 1.10.4.RELEASE
具體的版本對應查詢前面的文檔。