前提
这篇文章是《SpringBoot2.x入门》专辑的第1篇文章,使用的SpringBoot
版本为2.3.1.RELEASE
,JDK
版本为1.8
。
主要梳理一下SpringBoot2.x
的依赖关系和依赖的版本管理,依赖版本管理是开发和管理一个SpringBoot
项目的前提。
SpringBoot
其实是通过starter
的形式,对spring-framework
进行装箱,消除了(但是兼容和保留)原来的XML
配置,目的是更加便捷地集成其他框架,打造一个完整高效的开发生态。
SpringBoot依赖关系
因为个人不太喜欢Gradle
,所以下文都以Maven
举例。
和SpringCloud的版本(SpringCloud的正式版是用伦敦地铁站或者说伦敦某地名的英文名称作为版本号,例如比较常用的F版本Finchley就是位于伦敦北部芬奇利)管理不同,SpringBoot的依赖组件发布版本格式是:X.Y.Z.RELEASE。因为SpringBoot组件一般会装箱为starter,所以组件的依赖GAV一般为:org.springframework.boot:spring-boot-starter-${组件名}:X.Y.Z.RELEASE,其中X是主版本,不同的主版本意味着可以放弃兼容性,也就是SpringBoot1.x和SpringBoot2.x并不保证兼容性,而组件名一般是代表一类中间件或者一类功能,本文来源gao*daima.com搞@代#码&网6如data-redis(spring-boot-starter-data-redis,提供Redis访问功能)、jdbc(spring-boot-starter-jdbc,提供基于JDBC驱动访问数据库功能)等等。以SpringBoot当前最新的发布版本2.3.1.RELEASE的org.springframework.boot:spring-boot-starter:jar:2.3.1.RELEASE为例,用mvn dependency:tree分析它的依赖关系如下:
这个依赖树也印证了starter
是基于Spring
项目装箱和扩展的。
SpringBoot依赖管理
如果使用Spring Initializr创建一个SpringBoot
项目的话,那么会发现项目的POM
文件中会加入了一个parent
元素:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
其实spring-boot-starter-parent
相当于作为了当前项目的父模块,在父模块里面管理了当前指定的SpringBoot
版本2.3.1.RELEASE
所有依赖的第三方库的统一版本管理,通过spring-boot-starter-parent
上溯到最顶层的项目,会找到一个properties
元素,里面统一管理Spring
框架和所有依赖到的第三方组件的统一版本号,这样就能确保对于一个确定的SpringBoot
版本,它引入的其他starter
不再需要指定版本,同时所有的第三方依赖的版本也是固定的。如项目的POM
文件如下:
<!-- 暂时省略其他的配置属性 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies>