SpringBoot学习笔记(二)——starter

Spring Boot中的starter是Spring Boot的神器之⼀,Spring Boot提⾼了很多的starter,⽽每个starter
其实就是⼀个pom.xml⽂件。
⽐如在我们项⽬的pom.xml⽂件中,我们依赖了
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>
这段相当于我们的⼯程依赖了spring-boot-starter-web,但是我们并没有指定具体的version,那到底
依赖的是哪个版本的spring-boot-starter-web呢?
这就是由<parent>控制的。
<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>3.0.0-M1</version>
</parent>
这段代码是在给我们⾃⼰的⼯程指定了⼀个⽗⼯程,那这个⽗⼯程在哪呢?
Maven会先从本地仓库根据groupId和artifactId看是否有匹配的Jar包,如果没有就会进⾏下载,⽐如在
我电脑的.m2中就已经有了。也可以在IDEA中用ctrl+鼠标左键点击的方式来看父工程的依赖文件。
这个⽂件夹就是我们项⽬⼯程的⽗⼯程,我们的项⽬可以直接⽤⽗⼯程中所提供的。
那⽗⼯程中有什么东⻄呢?
其实就是⼀个pom⽂件。
所以,在我们的项⽬中,只要加上上面这段代码,
就相当于引⼊了spring-boot-starter-parent-3.0.0-M1.pom这个pom⽂件。
在spring-boot-starter-parent-3.0.0-M1.pom中有很对多内容,其中最重要的是:
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>3.0.0-M1</version>
  </parent>
  <artifactId>spring-boot-starter-parent</artifactId>
  <packaging>pom</packaging>
  <name>spring-boot-starter-parent</name>
  <description>Parent pom providing dependency and plugin management for
applications built with Maven</description>
  <properties>
    <java.version>17</java.version>
    <resource.delimiter>@</resource.delimiter>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
  </properties>
⼜指定了⼀个⽗⼯程,以及⼀些properties,⽐如java.version为17。也就是,我们⾃⼰项⽬的⽗⼯程为spring-boot-starter-parent-3.0.0-M1,⽽它的⽗⼯程为spring-boot-dependencies。
同样,我们可以在仓库中找到spring-boot-dependencies。
进⽽看看spring-boot-dependencies⼜是什么?
其实也就是⼀个pom⽂件,但是这个⽂件的内容就⾮常⾮常关键,因为它管理了Spring Boot默认⽀持的所有依赖以及对应的版本。
就是因为了有了这个pom⽂件,在我们⾃⼰项⽬的pom⽂件中,如果想要⽤某个依赖,只要这个依赖在spring-boot-dependencies-3.0.0-M1.pom中提供了,那你就可以不写版本,就相当于⽤的Spring
Boot给你提供的版本。
回到我们的项⽬,所以我们可以不写version。那spring-boot-starter-web这个starter⾥⾯⼜有什么呢?⾸先我们知道,这个依赖表示,我们是⼀个Spring Boot的web⼯程,正常来说,搭建⼀个web⼯程,是要依赖很多东⻄的,⽐如tomcat,spring-web,spring-webmvc等等依赖,⽽这就是spring-boot-starter-web的作⽤,spring-boot-starter-web的作⽤就是帮我们提前把我们要开发⼀个web应⽤的依
赖都写好了,我们只要依赖spring-boot-starter-web,就相当于了依赖其他很多相关的依赖。
Spring Boot真的很贴⼼。
除开web场景,还有很多其他场景也是类似的,所以Spring Boot默认提供了很多starter,具体可以看官⽹的统计:https://docs.spring.io/spring-boot/docs/3.0.0-M1/reference/html/using.html#using.build-systems.starters。值得注意的是,Spring Boot官⽅虽然提供了很多starter,但是有时可能仍然需要第三⽅来来⾃⼰实现⼀个starter并提供出来,对于这种情况,Spring Boot是有规范的,Spring Boot官⽅默认提供的starter命名格式为 spring-boot-starter-* ,第三⽅⾃⼰实现的starter的命名格式为*-spring-boot-starter 。
 
 
 
posted @ 2022-09-13 19:10  一直学习的程序小白  阅读(87)  评论(0编辑  收藏  举报