Maven 继承

Maven继承允许在一个POM中定义一组公共配置,并允许其他POM从该POM继承这些配置。这样可以避免在多个POM中复制相同的配置,提高配置的复用性和维护性。继承是基于一个父POM和一个或多个子POMs的关系来定义的。

例如,我们有一个父模块parent,包含了所有子模块共同需要的配置信息和依赖管理信息,同时还有子模块child1,他们都需要使用到父模块中定义的依赖和插件信息,同时他们自己也需要定义一些特定的依赖和插件信息。这时候,我们可以将共同的配置信息和依赖管理信息放在parent中,然后让child1继承parent中的配置信息,如下所示:

parent模块pom.xml文件:

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.parent</groupId>
  <artifactId>parent</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <dependencies>
    <!-- 共同需要的依赖信息 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <!-- 共同需要的插件信息 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

child1模块pom.xml文件:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.example.parent</groupId>
    <artifactId>parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>
  <groupId>com.example.child1</groupId>
  <artifactId>child1</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <dependencies>
    <!-- 子模块特定的依赖信息 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.3.3</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <!-- 子模块特定的插件信息 -->
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>2.4.2</version>
      </plugin>
    </plugins>
  </build>
</project>