maven的传递依赖与scope关系
项目里有个common工程,其他模块会通过maven依赖方式引入,本想在common中依赖test用的jar,如junit,这样其他引入common就可以传递依赖common的test用jar,就不用自己再引入,反正都要用到。但是却发现scope为test的jar无法通过传递依赖,看了看maven官网对于传递依赖与scope的关系:
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 depen
dency in the main project with the scope listed at the intersection. If no scope is listed, it means the dependency will be omitted.
大致的意思是工程A的依赖的scope如第一行,工程B引入了工程A且scope为左侧第一列,那么工程A传递到工程B的依赖的scope将如表格中交叉项所示
有点抽象……
举个例子:
下面是一个工程A的依赖,junit测试用,jdbc驱动runtime用,servlet容器会提供,lang3编译就要使用
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>com.springsource.oracle.jdbc</artifactId>
<version>11.1.0.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
</dependencies>
在工程B的pom中引入工程A,scope为compile,工程B会得到A的传递依赖
<dependency>
<groupId>hello</groupId>
<artifactId>A</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
结果:
jdbc[runtime] runtime传递过来还是runtime,如果编译期需要用的话还是要显式指定
lang3[compile]
proivide与test并不会传递,解释了开头的问题。
工程B中引入A,scope为provided
<dependency>
<groupId>hello</groupId>
<artifactId>A</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
结果:
jdbc[provided]
lang3[provided]
同理,工程B中引入A,scope为runtime或test,传递依赖的scope都将是runtime或test。
总结
- scope为test或provide的依赖不会传递,所以要多个工程指定相同的test依赖还是使用parent pom好了
- scope为runtime的依赖被compile传递后还是runtime