4.依賴的範圍、傳遞、排除、衝突(慕課網)
一.依賴範圍
一個專案要想使用別的jar包提供的功能,需要通過依賴將jar包引入到專案的classpath路徑中,maven中提供了編譯、測試、執行三種classpath,因此所以scope的值就是控制與三種classpath的關係。目前可用5個值:
• compile,預設值,適用於所有階段。
• provided,類似compile,編譯和測試時有效,最後是在執行的時候不會被加入。官方舉了一個例子。比如在JavaEE web專案中我們需要使用servlet的API,但是呢Tomcat中已經提供這個jar,我們在編譯和測試的時候需要使用這個api,但是部署到tomcat的時候,如果還加入servlet構建就會產生衝突,這個時候就可以使用provided。
• runtime,適用執行和測試階段,如JDBC驅動。
• test,只在測試時使用,用於編譯和執行測試程式碼,不會隨專案釋出。
• system,與本機系統相關聯,可移植性差。編譯和測試時有效。
• import,匯入的範圍,它只在使用dependencyManagement中,表示從其他pom中匯入dependecy的配置。
例子:把A中的構建匯入到B中。
<project> <modelVersion>4.0.0</modelVersion> <groupId>maven</groupId> <artifactId>B</artifactId> <packaging>pom</packaging> <name>B</name> <version>1.0</version> <dependencyManagement> <dependencies> <dependency> <groupId>maven</groupId> <artifactId>A</artifactId> <version>1.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project>
二.依賴傳遞
在正常開發中,我們也會封裝maven構建供小夥伴們使用,在我們使用自定義的構建中,那麼我們自定義的構建中依賴的構建,也會依賴傳遞過來。
在maven的install命令小結中,已經在demo1專案中引入了demo的jar包,下面來演示一下依賴傳遞。
1.執行mvn install將demo1專案打包到本地倉庫中
2.新建一個demo2專案,在專案中引入demo1的jar包
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>com.steven.maven</groupId><!--專案的包名--> <artifactId>demo1</artifactId><!--專案的模組名(專案名)--> <version>1.0-SNAPSHOT</version><!--快照版本--> </dependency> </dependencies>
3.編譯demo2,可以看到demo和demo1的jar都被載入到專案中來了
三.依賴排除
上面演示了傳遞依賴,但是如果我們只需要依賴demo1 並不想依賴demo怎麼辦呢?這個時候就要是用exclusions 排除依賴列表。
在demo2中排除依賴demo的pom.xml配置
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.steven.maven</groupId><!--專案的包名-->
<artifactId>demo1</artifactId><!--專案的模組名(專案名)-->
<version>1.0-SNAPSHOT</version><!--快照版本-->
<!--排除依賴傳遞列表 -->
<exclusions>
<exclusion>
<groupId>com.steven.maven</groupId>
<artifactId>demo</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
四.依賴衝突(短路優先)
由於依賴的傳遞性,就會產生依賴衝突,maven採用最短路徑和先宣告先使用策略來解決。 比如,在demo中新增一個6.02版本的mysql依賴,在demo1中新增一個6.06版本的mysql依賴。
1. 在demo中新增一個6.02版本的mysql依賴,重新install
2. 在demo1中新增一個6.06版本的mysql依賴,重新install
3. demo2依賴demo1, demo1依賴demo,此時根據短路優先原則,demo2則會依賴6.06版本
五.依賴衝突(先宣告先使用)
1.去除依賴
2.在demo2中依次引入demo和demo1依賴
demo依賴6.02版本,demo1依賴6.06版本,根據先宣告先使用原則 demo2則應該依賴demo的6.02版本。