暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Maven的scope作用域你知道么

小薛博客 2023-02-07
468

Maven的scope作用域

maven的scope一共包括:compile
runtime
test
system
provided
import

1、compile

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.4.1</version>
  <scope>compile</scope>
</dependency>

compile是默认值,当我们引入依赖时,如果标签没有指定,那么默认就是complie
。 compile表示被依赖项目需要参与当前项目的编译,包括后续的测试,运行周期也参与其中,同时打包的时候也会包含进去。是最常用的,所以也是默认的。

2、runtime

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.46</version>
   <scope>runtime</scope>
 </dependency>

runtime表示被依赖项目无需参与项目的编译,不过后期的测试和运行周期需要其参与。与compile相比,跳过编译而已。 数据库的驱动包一般都是runtime,因为在我们在编码时只会使用JDK提供的jdbc接口,而具体的实现是有对应的厂商提供的驱动(如mysql驱动),实在运行时生效的,所以这类jar包无需参与项目的编译。

3、test

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
   <scope>test</scope>
</dependency>

test表示只会在测试阶段使用,在src/main/java里面的代码是无法使用这些api的,并且项目打包时,也不会将"test"标记的打入"jar"包或者"war"包。

4、system

<dependency>
    <groupId>com.dm</groupId>
    <artifactId>dmjdbc7</artifactId>
    <version>1.7.0</version>
    <scope>system</scope>
    <systemPath>${pom.basedir}/src/main/plugins/Dm7JdbcDriver17.jar</systemPath>
</dependency>

system依赖不是由maven仓库,而是本地的jar包,因此必须配合systemPath标签来指定本地的jar包所在全路径。这类jar包默认会参与编译、测试、运行,但是不会被参与打包阶段。如果也想打包进去的话,需要在插件里做配置<includeSystemScope>
true</includeSystemScope>

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
     <!--设置为true,以便把本地的system的jar也包括进来-->
        <includeSystemScope>true</includeSystemScope>
    </configuration>
</plugin>

5、provided

<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
   <scope>provided</scope>
</dependency>

provided表示的是在编译和测试的时候有效,在执行(mvn package)进行打包成war、jar包的时候不会加入,比如:servlet-api,因为servlet-api,tomcat等web服务器中已经存在,如果在打包进去,那么包之间就会冲突

6、import

<dependencyManagement>
  <dependencies>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-dependencies</artifactId>
     <version>2.1.1.RELEASE</version>
     <type>pom</type>
     <scope>import</scope>
 </dependency>
 </dependencies>
</dependencyManagement>

import比较特殊,他的作用是将其他模块定义好的 dependencyManagement 导入当前 Maven 项目 pom 的 dependencyManagement 中,都是配合<type>pom</type>
来进行的。所以import作用的是pom类型,不是jar包。


文章转载自小薛博客,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论