问题:(1)为什么导入dependency时不需要指定版本?
在Spring Boot入门程序中,项目pom.xml文件有两个核心依赖,分别是spring-boot-starterparent和spring-boot-starter-web,关于这两个依赖的相关介绍具体如下
spring-boot-starter-parent
我们知道在创建spring boot项目时,如果选的spring initializr去创建项目 会自动创建parent节点
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
上述代码中,将spring-boot-starter-parent依赖作为Spring Boot项目的统一父项目依赖管理,并 将项目版本号统一为2.2.9.RELEASE,该版本号根据实际开发需求是可以修改。
点击 spring-boot-starter-parent进去看里面有什么首先看 spring-boot-starter-parent 的 parent节点
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${revision}</version>
<relativePath>../../spring-boot-dependencies</relativePath>
</parent>
再次点击spring-boot-dependencies 进去查看 可以看到在这里进行了版本控制,明确了不同jar的版本是多少,因此可以在外部真正使用时不需要指定版本。
问题一总结
spring-boot-starter-parent 通过继承 spring-boot-dependencies 从而实现了SpringBoot的版本依 赖管理,所以我们的SpringBoot工程继承spring-boot-starter-parent后已经具备版本锁定等配置了,这也 就是在 Spring Boot 项目中部分依赖不需要写版本号的原因
(2)问题2: spring-boot-starter-parent父依赖启动器的主要作用是进行版本统一管理,那么项目 运行依赖的JAR包是从何而来的?
点击 spring-boot-starter-web查看其依赖的jar
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
从上述代码可以发现,spring-boot-starter-web依赖启动器的主要作用是打包了Web开发场景所需的底 层所有依赖(基于依赖传递,当前项目也存在对应的依赖jar包)正是如此,在pom.xml中引入spring-boot-starter-web依赖启动器时,就可以实现Web场景开发,而 不需要额外导入Tomcat服务器以及其他Web依赖文件等。
Spring Boot除了提供有上述介绍的Web依赖启动器外,还提供了其他许多开发场景的相关依赖, 我们可以打开Spring Boot官方文档,搜索“Starters”关键字查询场景依赖启动器
问题二总结
每个springboot start中都引入了,所需的底 层所有依赖(基于依赖传递,当前项目也存在对应的依赖jar包),这样就能在 引入一个依赖就能实现引入所需的所有依赖,方便管理,简洁明了还能去除重复的依赖。