spring boot示例_Spring Boot REST示例

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.
    new spring starter project

    如下图所示,创建新的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 rest maven dependencies

    下一个屏幕要求添加除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.
    spring initializr project url

    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,我们可以使用它通过命令行轻松地创建此项目。
    Spring Initializr项目网址

    这是完整的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 {

	@Autowired
	private 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完成了所有配置,我们只需要专注于业务逻辑。 您可以从下面的链接下载最终项目。

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

spring boot示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值