[Spring Boot 系列教程] 目录
依赖管理
在上一篇文章中,我们介绍过 Spring Boot
将会帮助我们管理依赖,实际上,Spring Boot
是通过 BOM
(Bills of Materials) 的形式管理 Jar
包之间的依赖关系,对于 BOM
在此处不做过多介绍,有兴趣的可以参考官方文档。Spring Boot
为我们提供了一系列的 Starter 用于依赖的管理和对框架进行默认设置,下图简单的介绍了 Starter
所做的事情:
Maven
Maven 用户可以通过继承 spring-boot-starter-parent
,就可以轻松集成 Spring Boot
。同样的,我们还是通过 在线工具 生成项目脚手架,这次我们选择构建工具为 Maven
,其它的配置都和上一篇文章相同:
将项目下载到本地,解压并导入到 IDE 中,以下是工具生成的 POM
文件:
4.0.0
org.springframework.boot
spring-boot-starter-parent
1.5.19.RELEASE
com.docs4dev.springboot
demo02
0.0.1-SNAPSHOT
demo02
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
其中最重要的就是:
org.springframework.boot
spring-boot-starter-parent
1.5.19.RELEASE
当我们查看 spring-boot-starter-parent
时,会发现它又继承了另一个 pom
:spring-boot-dependencies
,在这个文件中,就定义了 Spring Boot
各种依赖包的版本号:
5.14.5
2.7.7
1.9.71
1.5.6
1.8.13
2.2
同时它定义了 dependencyManagement
:
org.springframework.boot
spring-boot
1.5.19.RELEASE
org.springframework.boot
spring-boot
test-jar
1.5.19.RELEASE
<!--省略其它-->
正是因为有了这些预定义数据,所以在我们使用 Spring Boot
进行开发的时候,才不用去关心各种框架之间的冲突问题。
如果我们想自行指定某个框架的依赖版本时,只需要在自己的 pom
文件中覆盖 Spring Boot
的属性即可,如:
Fowler-SR2
当我们使用 maven
作为构建工具的时候,只需要使我们自己的 pom
继承 spring-boot-starter-parent
,就可以使用 Spring Boot
为我们提供的各种特性了。但是某些时候,我们的 pom
可能已经继承了其它的 pom
,这个时候,我们还可以导入 Spring Boot
的 spring-boot-dependencies
来实现依赖管理:
org.springframework.boot
spring-boot-dependencies
2.1.0.RELEASE
pom
import
但是此种方式将 不支持 属性覆盖,所以如果你需要修改某个依赖的版本时,需要在 dependencyManagement
中添加相关依赖以覆盖 Spring Boot
的默认配置,如:
org.springframework.data
spring-data-releasetrain
Fowler-SR2
pom
import
org.springframework.boot
spring-boot-dependencies
2.1.0.RELEASE
pom
import
Spring Boot Maven 插件
同时,Spring Boot
还提供了插件来运行我们的应用:
org.springframework.boot
spring-boot-maven-plugin
它提供了几个 maven goal
:
-
spring-boot:build-info
:生成Actuator
使用的构建信息文件build-info.properties
-
spring-boot:help
:展示插件的帮助信息 -
spring-boot:repackage
: 在mvn package
之后,再次打包可执行的jar/war
,同时保留mvn package
生成的jar/war
为.origin
-
spring-boot:run
: 运行Spring Boot
程序 -
spring-boot:start
:在mvn integration-test
阶段,进行 Spring Boot 应用生命周期的管理 -
spring-boot:stop
:在mvn integration-test
阶段,进行 Spring Boot 应用生命周期的管理
Gradle
gradle
与 maven
只是配置方式稍微有些不同:
buildscript {
ext {
springBootVersion = '1.5.19.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
group = 'com.docs4dev.springboot'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
testCompile 'org.springframework.boot:spring-boot-starter-test'
}
org.springframework.boot
插件将会自动应用 Dependency Management Plugin 用于管理依赖,其它的都是基础的 gradle
配置项,在此就不做过多讲解。
结语
本篇文章介绍了如何使用 maven
以及 gradle
创建 Spring Boot
项目,在下一篇文章中,将介绍 Spring Boot
项目的打包和运行。
- 源码(maven)
- 源码(gradle)