通过示例说明 Maven 中的 scope 规则

Maven 中的 scope 规则指定了依赖项的使用范围,即在何时和何地使用依赖项。下面是一些示例说明maven scope 规则:

  1. compile:compile 是默认的 scope 规则,表示依赖项在编译、测试和运行时均可用。例如:
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
</dependency>
  1. provided:provided 表示依赖项在编译和测试时可用,但在运行时由 JDK 或服务器提供。例如:
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.0</version>
    <scope>provided</scope>
</dependency>
  1. runtime:runtime 表示依赖项在运行时可用,但在编译和测试时不需要。例如:
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.5</version>
    <scope>runtime</scope>
</dependency>
  1. test:test 表示依赖项仅在测试代码中可用。例如:
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
  1. system:system 表示依赖项是由本地系统上的特定文件提供的,通常是一个 JAR 文件。例如:
<dependency>
    <groupId>com.example</groupId>
    <artifactId>example-library</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>/path/to/example-library.jar</systemPath>
</dependency>
  1. import:import 只在 pom 文件的 dependencyManagement 部分使用,表示从其他项目中导入依赖项的版本号等信息,而不是把依赖项本身添加进来。例如:
<dependencyManagement>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-core</artifactId>
         <version>5.1.9.RELEASE</version>
         <scope>import</scope>
      </dependency>
   </dependencies>
</dependencyManagement>

通过明确指定依赖项的 scope 规则,可以使项目更加清晰和可维护。

猜你喜欢

转载自blog.csdn.net/ChinaLiaoTian/article/details/130502939
今日推荐