工程的继承

工程的继承

继承描述的是两个工程间的关系,与java中的继承相似,子工程可以继承父工程中的配置信息,常见于依赖关系的继承。

作用:

子工程的开发步骤

  1. 创建Maven模块,设置打包类型为pom

    <packaging>pom</packaging>
    

    注意事项:建议父工程打包方式为pom

  2. 在父工程的pom文件中配置依赖关系(子工程将沿用父工程中的依赖关系)

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        ...
    </dependencies>
    
  3. 配置子工程中可选的依赖关系

    <!--定义依赖管理-->
    <dependencyManagement>
        <dependencies>
            <!--代表子类不一定使用,子工程要用需要在子工程中声明,但不用写版本号-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
  4. 在子工程中配置当前工程所继承的父工程

    <!--配置当前工程继承自parent工程-->
    <parent>
        <groupId>com.charley</groupId>
        <artifactId>maven_01_parent</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../maven_01_parent/pom.xml</relativePath>
    </parent>
    
  5. 在子工程中配置使用父工程中可选依赖的坐标

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    

    注意事项:子工程中使用父工程的可选依赖时,仅需要提供群组id和项目id,无需提供版本,版本由父工程统一提供,避免版本冲突子工程中还可以定义父工程中没有定义的依赖关系。

继承与聚合的区别