您的位置:首页 > 其它

maven的依赖范围

2016-07-15 09:24 309 查看
Dependency scope 是用来限制Dependency的作用范围的, 影响maven项目在各个生命周期时导入的package的状态。
自从2.0.9后,新增了1种,现在有了6种scope:
compile
默认的scope,表示 dependency
都可以在生命周期中使用。而且,这些dependencies 会传递到依赖的项目中。
provided
跟compile相似,但是表明了dependency 由JDK或者容器提供,不需要打包到war文件中。例如Servlet AP和一些Java EE
APIs。这个scope 只能作用在编译和测试时,同时没有传递性。
runtime
表示dependency不作用在编译时,但会作用在运行和测试时
test
表示dependency作用在测试时,不作用在运行时。
system
跟provided
相似,但是在系统中要以外部JAR包的形式提供,maven不会在repository查找它。
注意该范围是不推荐使用的(你应该一直尽量去从公共或定制的 Maven 仓库中引用依赖)。
例如:

<project>
 ...
 <dependencies>
  <dependency>
   <groupId>javax.sql</groupId>
   <artifactId>jdbc-stdext</artifactId>
   <version>2.0</version>
   <scope>system</scope>
   <systemPath>${java.home}/lib/rt.jar</systemPath>
  </dependency>
 </dependencies>
 ...
</project>


import(Maven 2.0.9 之后新增)
它只使用在<dependencyManagement>中,表示从其它的pom中导入dependency的配置。
<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>
<dependency>
<groupId>test</groupId>
<artifactId>d</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
B项目导入A项目中的包配置


此外,为了精确的控制依赖包,可以使用依赖的排除功能
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.bocheng</groupId>
<artifactId>helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>xxx</groupId>
<artifactId>yyy</artifactId>
</exclusion>
</exclusions>
</dependency>


有些项目的jar包不是在maven服务器上能够下载的,那么需要将这样的包放在项目的lib目录下,不过这样会导致maven打包时找不到包,报错。可以通过下面的配置解决这个问题。
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
<compilerArguments>
<extdirs>src\main\webapp\WEB-INF\lib</extdirs>
</compilerArguments>
</configuration>
</plugin>
</plugins>
</build>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: