1:不同scope範圍介紹
Compile:
默認就是compile. Compile表示當前依賴在編譯/測試/運行這三種classpaths下都有效,是一個比較強的依賴。
Provided:
provided在編譯/測試的classpath下有效,在運行的classpath下無效。
如:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
JavaWeb項目在編譯/測試的classpath下需要導入依賴Servlet API,但在運行的時候服務器容器中已經存在ServletAPI依賴。
runtime:
在運行/測試對應的classpaths下有效,在編譯對應的classpaths下無效
如:
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
<scope>runtime</scope>
</dependency>
代碼裏沒有直接引用而是根據配置在運行時動態加載並實例化的情況。雖然把runtime改爲compile也是可以的,但使用runtime的好處是可以避免在運行的時候意外的引用原本應該動態加載的包。如此處的JDBC連接池
Test:
Test在測試的classpath下有效
如:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13-beta-3</version>
<scope>test</scope>
</dependency>
當前的依賴scope爲test,那麼表示這個依賴只有在進行代碼單元測試的時候纔會使用
System:
System元素與provided元素使用範圍相同,但它的依賴不會從maven倉庫中下載,而是從本地路徑獲取,通過systempath指定本地文件jar包路徑。
Import:
這個scope只支持<dependencyManagement>
中dependency的類型爲pom的節點。
如:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
以上的寫法與下面的寫法一致:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
以上兩種寫法都可以爲Springboot相關的依賴項提供默認的依賴版本
2:依賴傳遞介紹
Each of the scopes (except for import) affects transitive dependencies in different ways, as is demonstrated in the table below. If a dependency is set to the scope in the left column, transitive dependencies of that dependency with the scope across the top row will result in a dependency in the main project with the scope listed at the intersection. If no scope is listed, it means the dependency will be omitted.
compile | provided | runtime | test | |
---|---|---|---|---|
compile | compile(*) | - | runtime | - |
provided | provided | - | provided | - |
runtime | runtime | - | runtime | - |
test | test | - | test | - |
對以上圖標做簡單的解釋,假設有三個依賴項目A、B、C,其中A依賴B,B依賴C.
假設B在A中的依賴scope爲compile,
當C在B中的依賴scope爲compile時, C在A中的依賴scope爲compile;
當C在B中的依賴scope爲provided時,C在A中沒有依賴關係;
當C在B中的依賴scope爲runtime時, C在A中的依賴scope爲runtime;
當C在B中的依賴scope爲test時, C在A中沒有依賴關係;