如何在项目继承了父项目的情况下引入SpringBoot?

项目想引入SpringBoot框架,我们可以通过继承spring-boot-starter-parent来实现。如下:

xml 复制代码
<!-- Inherit defaults from Spring Boot -->
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>3.2.0</version>
</parent>

但有时候项目可能需要有公司标准的父项目需要继承,这样我们就没办法使用上面的方式来引入SpringBoot了。不过,我们可以通过下面的方式来引入SpringBoot:

xml 复制代码
<dependencyManagement>
    <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>3.2.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

为什么通过第二种方式能够实现同样的目的?

那我们先看第一种通过继承的方式引入SpringBoot做了什么?

<parent>标签的作用是使一个项目继承父项目中pom的所有配置。

然后我们点开spring-boot-starter-parent父项目的pom看到所有的依赖都在<dependencyManagement>中声明,并且没有在dependencies中声明依赖。

就是说我们的项目继承了父项目pring-boot-starter-parent<dependencyManagement>标签的所有配置依赖。

第二种配置方式做了什么?

import

This scope is only supported on a dependency of type pom in the <dependencyManagement> section. It indicates the dependency is to be replaced with the effective list of dependencies in the specified POM's <dependencyManagement> section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

上面为maven官方文档对于import作用域的描述。意思是:import仅支持在<dependencyManagement><dependency>中使用。这表示这个依赖会被替换成这个依赖的<dependencyManagement>中配置的依赖。

简单的说就是,当我们使用第二种配置方式来引入SpringBoot,那么会将spring-boot-starter-parent依赖的pom文件的<dependencyManagement>标签内配置的依赖全部替换到当前项目的<dependencyManagement>中。

这样,我们发现第一种方式和第二种方式实现的效果是一样的。

参考文档

Maven官方文档 - 对于依赖的scope的描述

Spring Boot官方文档 - 如何通过不继承parent的方式使用Spring Boot

相关推荐
Lionel_SSL2 小时前
《深入理解Java虚拟机》第三章读书笔记:垃圾回收机制与内存管理
java·开发语言·jvm
记得开心一点嘛2 小时前
手搓Springboot
java·spring boot·spring
老华带你飞3 小时前
租房平台|租房管理平台小程序系统|基于java的租房系统 设计与实现(源码+数据库+文档)
java·数据库·小程序·vue·论文·毕设·租房系统管理平台
独行soc3 小时前
2025年渗透测试面试题总结-66(题目+回答)
java·网络·python·安全·web安全·adb·渗透测试
脑子慢且灵3 小时前
[JavaWeb]模拟一个简易的Tomcat服务(Servlet注解)
java·后端·servlet·tomcat·intellij-idea·web
华仔啊4 小时前
SpringBoot 中 6 种数据脱敏方案,第 5 种太强了,支持深度递归!
java·后端
异常驯兽师5 小时前
Spring 中处理 HTTP 请求参数注解全解析
java·spring·http
连合机器人6 小时前
晨曦中的守望者:当科技为景区赋予温度
java·前端·科技
AD钙奶-lalala6 小时前
idea新建的项目new 没有java class选项
java·ide·intellij-idea
sheji34166 小时前
【开题答辩全过程】以 12306候补购票服务系统为例,包含答辩的问题和答案
java·eclipse