使用Spring Boot REST服务可以节省编写框架组件和样板代码的时间。
在此文中,我们将从头编写自己的Spring Boot REST 服务。当你希望专注于你的业务而不是花时间编写框架组件和样板代码,Spring Boot的自动配置带来很大的便利。
今天,我们将创建一个简单的RESTful服务。首先,让我们编写第一个Dog服务。创建Spring Boot项目的最快的方式就是使用Spring Initializr。
教程大纲:
-
创建一个Spring Boot项目
-
模拟数据来源
-
使用GET,POST,DELETE方法创建Dogs控制器。
-
查看Dogs服务的运行情况
注意:
-
使用模拟数据库代替真实的数据
-
这里有一篇关于 Spring REST 服务异常处理的文章
-
将单元测试排除在范围之外。(我们将在单独的教程中介绍REST服务的测试)。
1. 创建Spring Boot项目
让我们来编写基本的项目组件。
1.1 build.gradle
到目前为止,我们已经添加了spring-boot-starter-web—表示我们希望构建web应用程序—和Lombok依赖项。
Lombok 帮助您摆脱典型的样板式代码,我一直很喜欢使用它。我通常使用Lombok来避免编写构造函数、getter、setter等。访问Project Lombok以获得更多信息。
buildscript
{
ext
{
springBootVersion
=
'2.1.0.RELEASE'
}
repositories
{
mavenCentral
()
}
dependencies
{
classpath
(
"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
)
}
}
apply plugin
:
'java'
apply plugin
:
'eclipse'
apply plugin
:
'org.springframework.boot'
apply plugin
:
'io.spring.dependency-management'
group
=
'com.amitph.spring'
version
=
'0.0.1-SNAPSHOT'
sourceCompatibility
=
1.8
repositories
{
mavenCentral
()
}
dependencies
{
implementation
(
'org.springframework.boot:spring-boot-starter-web'
)
compile
(
'org.projectlombok:lombok:1.18.4'
)
testImplementat