spring boot示例

Spring Boot is an awesome module from Spring Framework. Once you are used to it, then working with Spring is a breeze because it takes care of all the spring container specific configurations and allows us to focus more on our application.

Spring Boot是Spring Framework的一个很棒的模块。 一旦习惯了,那么使用Spring是一件轻而易举的事,因为它可以处理所有特定于Spring容器的配置,并使我们可以将更多精力放在应用程序上。

REST web services are very popular these days, so in this tutorial, we will see how easily we can create a RESTful web service using Spring Boot.

REST Web服务如今非常流行,因此在本教程中,我们将看到使用Spring Boot创建RESTful Web服务的难易程度。

Spring Boot REST依赖关系 (Spring Boot REST Dependencies)

Since web services run on the server, apart from Spring Boot we need to add Spring MVC to our project. I am using Eclipse to create my basic spring boot project, but you can also use Spring Initializr.

由于Web服务在服务器上运行,因此除了Spring Boot之外,我们需要将Spring MVC添加到我们的项目中。 我正在使用Eclipse创建基本的Spring Boot项目,但是您也可以使用Spring Initializr 。

When we use Eclipse for creating Spring project, it actually uses Spring Initializr and configures it. Let’s get started.

当我们使用Eclipse创建Spring项目时,它实际上使用Spring Initializr并对其进行配置。 让我们开始吧。

Spring Boot REST项目 (Spring Boot REST Project)

  1. Create new Spring Starter Project as shown in below image. Eclipse should have Spring support for this, all the latest Eclipse release has built-in Spring support.

    如下图所示,创建新的Spring Starter Project。 Eclipse应该对此具有Spring支持,所有最新的Eclipse版本都具有内置的Spring支持。

  2. In the next popup screen, provide project basic details. I am using Maven, you can use Gradle too.
  3. Next screen asks to add dependencies apart from Spring Boot. Add “Web” dependencies and click next.

    下一个屏幕要求添加除Spring Boot以外的依赖项。 添加“ Web”依赖项,然后单击“下一步”。

  4. We could have click on Finish in the earlier screen, but clicking on next provides us the Spring Initializr URL that we can use to create this project easily through the command line.

    Here is the complete URL, you can just go to this URL in the browser and download the skeleton maven project that we have created so far.

    我们可以在前面的屏幕中单击“完成”,但是单击下一步将为我们提供Spring Initializr URL,我们可以使用它通过命令行轻松地创建此项目。

    这是完整的URL,您可以在浏览器中转到该URL并下载到目前为止我们创建的骨架Maven项目。

  5. Below image shows the contents of the auto-generated project.

    Most important of these is SpringBootRestApplication class that is configured as Spring Boot application and contains java main method. When we run this class, it automatically runs our project as Spring Boot Web project.

    If you will check the console logs, it should print Tomcat started on port(s): 8080 (http) with context path ''.

    其中最重要的是配置为Spring Boot应用程序并包含java main方法的SpringBootRestApplication类。 当我们运行此类时,它会自动将我们的项目作为Spring Boot Web项目运行。

    如果您将检查控制台日志,则应打印Tomcat started on port(s): 8080 (http) with context path ''

Now that our base Spring Boot REST application is ready, it’s time to add some endpoints and business logic to it.

现在我们的基本Spring Boot REST应用程序已经准备就绪,是时候添加一些端点和业务逻辑了。

We will use a java bean class for sending REST web service response. Here is the code for it.

我们将使用Java bean类来发送REST Web服务响应。 这是它的代码。

package com.journaldev.spring;import org.springframework.stereotype.Component;@Component
public class Person {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}

Spring REST端点配置 (Spring REST Endpoints Configuration)

We will create a @RestController and add some methods and annotate them with @RequestMapping. Below is our REST Controller class that exposes few GET and POST endpoints.

我们将创建一个@RestController并添加一些方法,并使用@RequestMapping对其进行注释。 下面是我们的REST Controller类,它公开了一些GET和POST端点。

package com.journaldev.spring;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class PersonController {@Autowiredprivate Person person;@RequestMapping("/")public String healthCheck() {return "OK";}@RequestMapping("/person/get")public Person getPerson(@RequestParam(name="name", required=false, defaultValue="Unknown") String name) {person.setName(name);return person;}@RequestMapping(value="/person/update", method=RequestMethod.POST)public Person updatePerson(@RequestParam(name="name", required=true) String name) {person.setName(name);return person;}}

Please go through the above class properly, this is the most important part of this tutorial. It’s very easy to understand what is happening here:

请正确地完成上述课程,这是本教程最重要的部分。 很容易理解这里发生了什么:

  • When we annotate the controller class with @RestController, Spring Boot scans it to find the REST endpoints to configure.当我们使用@RestController注释控制器类时,Spring Boot会对其进行扫描以查找要配置的REST端点。
  • @RequestMapping annotation on methods tells Spring to use this method as handler for any client requests. This is very important spring annotation, we can configure additional features such as HTTP methods supported, Content-Type of request, response content type etc. By default, GET method is supported and JSON response is returned.方法上的@RequestMapping注释告诉Spring将这个方法用作任何客户端请求的处理程序。 这是非常重要的spring注释,我们可以配置其他功能,例如支持的HTTP方法,请求的Content-Type,响应内容类型等。默认情况下,支持GET方法并返回JSON响应。

That’s it, our Spring Boot RESTful web service is ready to run and test.

就是这样,我们的Spring Boot RESTful Web服务已经可以运行和测试了。

Spring Boot REST Web服务测试 (Spring Boot REST Web Service Test)

When you will run the main class, check the logs for endpoints configuration.

当您运行主类时,请检查日志以了解端点配置。

2018-05-25 16:20:15.961  INFO 11802 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.journaldev.spring.PersonController.healthCheck()
2018-05-25 16:20:15.962  INFO 11802 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/person/get]}" onto public com.journaldev.spring.Person com.journaldev.spring.PersonController.getPerson(java.lang.String)
2018-05-25 16:20:15.962  INFO 11802 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/person/update],methods=[POST]}" onto public com.journaldev.spring.Person com.journaldev.spring.PersonController.updatePerson(java.lang.String)

All seems good, GET requests can be tested in the browser itself.

一切似乎都不错,可以在浏览器本身中测试GET请求。

I am using Postman Chrome app for testing POST requests.

我正在使用Postman Chrome应用测试POST请求。

Spring Boot REST JSON请求响应 (Spring Boot REST JSON Request Response)

JSON is the standard messaging format for REST web services, I didn’t liked that we are accepting String as POST request, let’s change our method to accept JSON request.

JSON是REST Web服务的标准消息传递格式,我不喜欢我们接受String作为POST请求,让我们将方法更改为接受JSON请求。

@RequestMapping(value="/person/update", method=RequestMethod.POST, consumes = "application/json")public Person updatePerson(@RequestBody Person p) {person.setName(p.getName());return person;
}

That’s it, couple of changes in method annotations and we are done. Now when you will run the main program, it will produce following output for endpoint configuration.

就这样,方法注释中的几个更改就完成了。 现在,当您运行主程序时,它将为端点配置生成以下输出。

2018-05-25 16:31:12.613  INFO 11813 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/person/update],methods=[POST],consumes=[application/json]}" onto public com.journaldev.spring.Person com.journaldev.spring.PersonController.updatePerson(com.journaldev.spring.Person)

Below image shows the Postman settings and input for the POST method call.

下图显示了Postman设置和POST方法调用的输入。

摘要 (Summary)

In this post, we learned how to use Spring Boot to create a RESTful web service. Spring Boot did all the configurations and we only had to focus on our business logic. You can download the final project from below link.

在本文中,我们学习了如何使用Spring Boot创建RESTful Web服务。 Spring Boot完成了所有配置,我们只需要专注于业务逻辑。 您可以从下面的链接下载最终项目。

Spring Boot REST Project.Spring Boot REST项目。
GitHub Repository.GitHub Repository下载该项目。

翻译自: https://www.journaldev.com/21127/spring-boot-rest-example

spring boot示例

spring boot示例_Spring Boot REST示例相关推荐

  1. spring cloud入门_Spring Boot 2.x基础教程:快速入门

    简介 在您第1次接触和学习Spring框架的时候,是否因为其繁杂的配置而退却了?在你第n次使用Spring框架的时候,是否觉得一堆反复黏贴的配置有一些厌烦?那么您就不妨来试试使用Spring Boot ...

  2. spring boot示例_Spring Boot完成示例

    spring boot示例 这篇文章提供了一个使用Spring Boot开发松耦合的REST服务的完整示例. 使用spring boot,我们可以开发可独立运行的生产就绪的Java应用程序,使其成为独 ...

  3. spring boot示例_Spring Boot上的Spring社交示例,或者我如何停止担心和喜欢自动配置...

    spring boot示例 对于Spring Boot 1.1.0.RC1,添加了自动配置和Spring Social的启动程序pom,这意味着我不必向pom添加一百个依赖关系,并且将为我处理许多毫无 ...

  4. spring boot注释_Spring Boot中的@SpringBootConfiguration注释

    spring boot注释 Spring Boot中的 @SpringBootConfiguration注释是一个类级别的注释,它指示此类提供了应用程序配置. 通常,具有main()方法的类最适合此注 ...

  5. spring boot缓存_Spring Boot和缓存抽象

    spring boot缓存 缓存是大多数应用程序的主要组成部分,只要我们设法避免磁盘访问,缓存就会保持强劲. Spring对各种配置的缓存提供了强大的支持 . 您可以根据需要简单地开始,然后进行更多可 ...

  6. spring boot 核心_Spring Boot 的 10 个核心模块

    作者:Java技术栈 链接:https://www.jianshu.com/p/11c54edc2d11 学习 Spring Boot 必须得了解它的核心模块,和 Spring 框架一样,Spring ...

  7. spring boot面试_Spring Boot面试问题

    spring boot面试 Today we will look into some spring boot interview questions and answers. So far, we h ...

  8. spring boot组件_Spring Boot Framework的关键组件和内部

    spring boot组件 In my previous post "Introduction to Spring Boot", we have discussed about S ...

  9. spring boot 缓存_Spring Boot 集成 Redis 实现数据缓存

    Spring Boot 集成 Redis 实现数据缓存,只要添加一些注解方法,就可以动态的去操作缓存了,减少代码的操作. 在这个例子中我使用的是 Redis,其实缓存类型还有很多,例如 Ecache. ...

最新文章

  1. oracle归档日志写满错误解决方法
  2. 互联网协议 — TLS — CA 认证
  3. 【译】Diving Into The Ethereum VM Part 5 — The Smart Contract Creation Process
  4. 程序员,你喜欢抽哪种香烟?(python数据分析)
  5. 物联网安全威胁及应对措施
  6. 【Luogu】P1896互不侵犯King(状压DP)
  7. Table 'barfoo_datacenter_config.parttemplates' doesn't exist------Mysql
  8. .Net Core 认证系统之基于Identity Server4 Token的JwtToken认证源码解析
  9. linux用户limit修改,linux – 使用cgroups作为用户设置用户创建的systemd范围的MemoryLimit...
  10. 什么是0day漏洞,1day漏洞和nday漏洞
  11. 查询和预测影响因子,这篇文章就够了
  12. 数据分析之数据预处理、分析建模、可视化
  13. 【爬虫】手把手教你写网络爬虫(1)
  14. python-将csv转txt
  15. CNCC——多模态会议
  16. C语言学习—杨辉三角的实现
  17. 3D游戏建模教程:Maya如何隐藏灯光
  18. IDEA默认JDK版本号变成11了
  19. 办理公司经营贷款需要什么条件呢?-民兴商学院
  20. SQL两张表如何关联

热门文章

  1. 2016届毕业生-毕业设计的相关事项
  2. WinSCP 连接 Ubuntu 拒绝的问题
  3. CSS背景图像的简单响应
  4. Java程序低手之关于泛型(Generic)
  5. 面向对象及os模块、socket模块
  6. Fiddler抓包【3】_设置断点修改
  7. 栈的应用--马踏棋盘-贪心加栈
  8. lua和torch的安装
  9. python课设答辩ppt_如何制作优秀的毕业论文答辩PPT
  10. (带区号)座机号正则_字符串处理之正则表达式(通俗易懂)