本篇将学习使用Spring boot 2框架创建REST API,该框架将JSON响应返回给客户端。在这个Spring Boot 2 REST API教程中,我们将逐步创建两个简单的GET和POST API并对其进行测试。

1. Maven依赖

首先,创建一个简单的maven Web项目并更新pom.xml文件中的spring boot依赖项。

重要的依赖关系是spring-boot-starter-parentspring-boot-starter-web。Starter Web依赖关系可传递地包含更多依赖关系来构建Web应用程序,例如spring-webmvc,spring-web,hibernate-validator,tomcat-embed-core,tomcat-embed-el,tomcat-embed-websocket,jackson-databind,jackson- datatype-jdk8,jackson-datatype-jsr310和jackson-module-parameter-names。

pom.xml

 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.howtodoinjava.demo</groupId>
  8. <artifactId>springbootdemo</artifactId>
  9. <version>0.0.1-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <name>SpringBootDemo</name>
  13. <description>Spring Boot2 REST API Demo for http://howtodoinjava.com</description>
  14.  
  15. <parent>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-parent</artifactId>
  18. <version>2.0.5.RELEASE</version>
  19. <relativePath />
  20. </parent>
  21.  
  22. <properties>
  23. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  24. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  25. <java.version>1.8</java.version>
  26. </properties>
  27.  
  28. <dependencies>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-web</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. </dependencies>
  39.  
  40. <build>
  41. <plugins>
  42. <plugin>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-maven-plugin</artifactId>
  45. </plugin>
  46. </plugins>
  47. </build>
  48.  
  49. </project>

2. Spring Boot 2 REST API控制器

  • 在Spring中,一个能够提供REST API请求的控制器类称为rest控制器。它应该使用@RestController注释进行注释。
  • 资源在@RequestMapping注释中指定。它可以在类级别和方法级别应用。添加类级别路径和方法级别路径后,将解析API的完整URI。
  • 我们应该总是编写produces 和consumes 属性来指定API的mediatype属性。

在给定的控制器中,我们有两种API方法。可以 根据需要添加更多方法。

  1. HTTP GET / employees - 返回employees列表。
  2. HTTP POST / employees - 在employees集合中添加employe。

EmployeeController.java

 
  1. package com.howtodoinjava.rest.controller;
  2.  
  3. import java.net.URI;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
  13.  
  14. import com.howtodoinjava.rest.dao.EmployeeDAO;
  15. import com.howtodoinjava.rest.model.Employee;
  16. import com.howtodoinjava.rest.model.Employees;
  17.  
  18. @RestController
  19. @RequestMapping(path = "/employees")
  20. public class EmployeeController
  21. {
  22. @Autowired
  23. private EmployeeDAO employeeDao;
  24.  
  25. @GetMapping(path="/", produces = "application/json")
  26. public Employees getEmployees()
  27. {
  28. return employeeDao.getAllEmployees();
  29. }
  30.  
  31. @PostMapping(path= "/", consumes = "application/json", produces = "application/json")
  32. public ResponseEntity<Object> addEmployee(@RequestBody Employee employee)
  33. {
  34. Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1;
  35. employee.setId(id);
  36.  
  37. employeeDao.addEmployee(employee);
  38.  
  39. URI location = ServletUriComponentsBuilder.fromCurrentRequest()
  40. .path("/{id}")
  41. .buildAndExpand(employee.getId())
  42. .toUri();
  43.  
  44. return ResponseEntity.created(location).build();
  45. }
  46. }

我们可以使用application.properties文件控制和自定义大量实现细节。但是为了简化这个演示,我将它留空。

3. @SpringBootApplication

我们的REST API框架已准备就绪。现在我们需要配置Spring来检测我们的其他控制器(使用自动扫描)并在嵌入式tomcat服务器中部署apis。值得庆幸的是,Spring boot通过使用自动配置的概念使所有这些事情变得非常简单。

自动配置尝试猜测和配置您可能需要的bean。自动配置类通常基于应用程序类路径中的jar和我们在@Configuration类中另外定义的bean来应用。

在这种情况下,它会做一些事情。

  1. 它检测spring-webmvc,因此配置默认的spring mvc应用程序bean。它有助于扫描和配置@RestController以及类似的注释。
  2. 它检测嵌入式tomcat jar,为我们配置嵌入式tomcat。
  3. 它检测JSON jar,以便为API配置JSON支持。

SpringBootDemoApplication.java

 
  1. package com.howtodoinjava.rest;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. @SpringBootApplication
  7. public class SpringBootDemoApplication {
  8.  
  9. public static void main(String[] args) {
  10. SpringApplication.run(SpringBootDemoApplication.class, args);
  11. }
  12. }

4.Model classes and DAO

这些类与REST没有直接关系。还是让我们来看看他们是如何写的。

Employee.java

 
  1. package com.howtodoinjava.rest.model;
  2.  
  3. public class Employee {
  4.  
  5. public Employee() {
  6.  
  7. }
  8.  
  9. public Employee(Integer id, String firstName, String lastName, String email) {
  10. super();
  11. this.id = id;
  12. this.firstName = firstName;
  13. this.lastName = lastName;
  14. this.email = email;
  15. }
  16.  
  17. private Integer id;
  18. private String firstName;
  19. private String lastName;
  20. private String email;
  21.  
  22. //Getters and setters
  23.  
  24. @Override
  25. public String toString() {
  26. return "Employee [id=" + id + ", firstName=" + firstName + ",
  27. lastName=" + lastName + ", email=" + email + "]";
  28. }
  29. }

Employees.java

 
  1. package com.howtodoinjava.rest.model;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class Employees
  7. {
  8. private List<Employee> employeeList;
  9.  
  10. public List<Employee> getEmployeeList() {
  11. if(employeeList == null) {
  12. employeeList = new ArrayList<>();
  13. }
  14. return employeeList;
  15. }
  16.  
  17. public void setEmployeeList(List<Employee> employeeList) {
  18. this.employeeList = employeeList;
  19. }
  20. }

DAO类使用静态列表来存储数据。这里我们需要实现实际的数据库交互。

EmployeeDAO.java

 
  1. package com.howtodoinjava.rest.dao;
  2.  
  3. import org.springframework.stereotype.Repository;
  4.  
  5. import com.howtodoinjava.rest.model.Employee;
  6. import com.howtodoinjava.rest.model.Employees;
  7.  
  8. @Repository
  9. public class EmployeeDAO
  10. {
  11. private static Employees list = new Employees();
  12.  
  13. static
  14. {
  15. list.getEmployeeList().add(new Employee(1, "Lokesh", "Gupta", "[email protected]"));
  16. list.getEmployeeList().add(new Employee(2, "Alex", "Kolenchiskey", "[email protected]"));
  17. list.getEmployeeList().add(new Employee(3, "David", "Kameron", "[email protected]"));
  18. }
  19.  
  20. public Employees getAllEmployees()
  21. {
  22. return list;
  23. }
  24.  
  25. public void addEmployee(Employee employee) {
  26. list.getEmployeeList().add(employee);
  27. }
  28. }

5. Spring Boot REST演示

要启动应用程序,请main()SpringBootDemoApplication类中运行该方法。它将启动嵌入式tomcat服务器。在服务器日志中,您将看到API已在spring上下文中注册。

Console

 
  1. s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/employees/],methods=[GET],produces=[application/json]}" onto public com.howtodoinjava.rest.model.Employees com.howtodoinjava.rest.controller. EmployeeController.getEmployees()
  2.  
  3. s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/employees/],methods=[POST], consumes=[application/json], produces=[application/json]}" onto public org.springframework.http.ResponseEntity <java.lang.Object> com.howtodoinjava.rest.controller. EmployeeController.addEmployee( com.howtodoinjava.rest.model.Employee )

5.1.HTTP GET /employees

服务器启动后,使用某个rest客户端访问API。

Springboot 2 REST API示例

Spring Boot REST HTTP GET
 

 

API响应

 
  1. {
  2. "employeeList": [
  3. {
  4. "id": 1,
  5. "firstName": "Lokesh",
  6. "lastName": "Gupta",
  7. "email": "[email protected]"
  8. },
  9. {
  10. "id": 2,
  11. "firstName": "Alex",
  12. "lastName": "Kolenchiskey",
  13. "email": "[email protected]"
  14. },
  15. {
  16. "id": 3,
  17. "firstName": "David",
  18. "lastName": "Kameron",
  19. "email": "[email protected]"
  20. }
  21. ],
  22. }

5.2.HTTP POST /employees

Springboot 2 REST API示例

Spring Boot REST HTTP POST 响应标头

 
  1. location: http://localhost:8080/employees/4
  2. content-length: 0
  3. date: Sat, 06 Oct 2018 04:33:37 GMT

再次点击GET请求,这次我们也将获得添加的员工。

Springboot 2 REST API示例

Spring Boot REST HTTP GET - update

相关文章: