Scope属性
scope
属性用于控制jar包处于的作用域范围,因为很多情况下我们使用的jar并不需要放入到最终的classpath
中以供程序运行中使用,所以可以通过scope
属性来控制。
test (测试)
当scope
的值是test
时,代表这个jar
包只在test
编译和test
运行时,才存在于classpath
当中。
例如:
当我将spring-boot-starter-web
这个jar的scope设置为test
的时候,jar
包中的org.springframework.web.context.request.RequestContextHolder
类只能在Maven
里的test
文件夹下进行使用,在main
源代码下是无法使用的。
compile (编译)
当scope
的值是compile
时,代表这个jar
包在程序编译和程序运行时,都存在于classpath
当中,并且在test
阶段也是可以继续使用的。
provided (已提供)
当scope
的值是provided
时,代表这个jar
包只在程序编译时,才存在于classpath
当中,
这意味着当前程序编译后,这个jar
在程序运行时,必须由运行时的classpath
进行提供,否则可能会出现类无法加载到或者方法不存在等错误,
所以当scope
的值是provided
时,意味这这个jar在程序运行时由其他地方进行提供,并最终存在于程序运行时的classpath
中。
system (系统)
system
代表这个jar
包由本项目进行路径指定提供,不会去远程仓库或者本地仓库中去搜索查找,这个对于一些公司内部或者第三方在仓库中无法进行查找的jar
包使用有效,使用方式如下:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/druid-1.1.10.jar</systemPath>
</dependency>
runtime (运行时)
runtime
代表这个jar
只在运行的时候存在于classpath
中,编译的时候不需要存在,例如JDBC
驱动,
一般只有在程序运行的时候通过Class.forName("com.mysql.jdbc.Driver");
进行加载。
import(导入)
import
只能在dependencyManagement
节点下使用,用于管理jar
包的版本依赖,例如:
<!--依赖管理,用于管理spring-cloud的依赖-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
spring-cloud-dependencies
是一个管理spring-cloud
下各个子模块的版本依赖jar,通过引入这个jar包后,
我们在项目的其他地方引入cloud
下的jar
时,就可以不用显示的指定版本了,这个地方会自动帮我们引入相应的版本进来,
例如:
我们项目中引入consul
的jar
,但是没有指定版本, 是因为在dependencyManagement
中帮我们进行管理啦。