2. Spring Boot 统一父pom处理

为什么需要统一的父pom

由于在项目中存在不同的模块,而模块间很可能引用一些共同的jar包,会很容易导致版本冲突。因此,需要一个统一的pom文件来作为父文件管理所有的依赖版本。

如何在Spring Boot中使用这样的pom文件

将项目从逻辑上划分为父项目和各模块,然后在各自的pom文件中配置其管理关系。

Step1: 父项目中的pom配置

  1. 首先必然是需要建立一个父项目,同时在其pom文件中将打包方式修改为pom:<package>pom</package>
  2. 添加spring boot的build方式。
<build>
  <finalName>parentboot</finalName>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <encoding>${project.build.sourceEncoding}</encoding>
      </configuration>
    </plugin>
  </plugins>
</build>

spring-boot-maven-plugin和maven-compiler-plugin的区别
前者直接将spring-boot程序打成可执行的jar包了,拿出来就直接通过命令行启动内置的tomcat,进而带动应用的启动。后者只是单纯的打包。

  1. 将其依赖方式等,修改为<dependencyManagement>的方式,同时在里面添加所有的Spring Boot的总依赖spring-boot-dependencies
<dependencyManagement>
        <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.0.0.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
  1. 如果想单独升级某个模块,而不依赖于spring-boot-dependencies的话,可以直接将该模块的依赖写在dependency之前,并且scope为import,类型为pom
<dependencyManagement>
    <dependencies>
        <!-- Override Spring Data release train provided by Spring Boot -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Fowler-SR2</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.0.0.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Step2: 创建子模块

  1. 直接使用spring的start建立一个子模块即可。
  2. 删除子模块pom文件的相关配置,追加spring boot web依赖包。

注意
此时会出现junit冲突的报错。因为Spring Boot在父项目中引入的依赖包是很全的,锁定了程序中很多依赖的版本。此时直接从子项目中删除其junit依赖即可

Step3: 一些其他的注意点

  1. 使用start生成的spring boot子项目,其pom文件中的<parent>标签需要修改为现在的父项目。这个不要忘了。
  2. 同样的,不要忘记在父项目中,通过module标签引入子模块。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容