用Spring Boot构建RESTFul API
libai 发布于 2021-04-05

在本文中,我们将逐步学习如何使用springboot构建restfulapi。我们还将在此过程中学习RestController、HTTP响应代码和最佳实践。

1. 项目设置

对于springboot项目的初始设置,应该使用springinitializer。阅读这里如何使用SpringInitializer设置SpringBoot项目
假设您选择maven作为构建项目。典型的pom.xml文件对于一个web项目这是:-
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>api</name>
    <description>Build RESTFul API using Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. 启用Web MVC

当您使用springboot项目时,在为您的项目启用springwebmvc方面没有太多工作要做。制造当然可以:-
您的系统中有spring boot starter web依赖项pom.xml文件或者构建.gradle
您正在应用程序启动程序类文件中使用@SpringBootApplication。
springboot是固执己见的,当它在类路径中看到web依赖时,它会设置API开发所需的所有必要的默认配置,这样您就可以专注于业务逻辑。

package com.example.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }

}

3. 构建RESTFul API

我们正在创建一个UserController类来为CRUD操作构建restfulapi。对你来说没什么理解:-
在类级别使用@RestController,它有助于为您绑定默认的HTTP转换器,例如,当您从控制器方法返回一个用户对象时,它负责将它们转换为JSON。
在类级别使用@RequestMapping,将api映射到URL。
在方法级别使用@RequestMapping的缩写,即@GetMapping、@PostMapping、@PutMapping、@DeleteMapping。
在方法级别使用@ResponseStatus获取适当的HTTP统计代码。
在这里使用UserService将工作委托给服务层

package com.example.api.controller;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public Users getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Long createUser(User user) {
        return userService.createUser(user);
    }

    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public void updateUser(@PathVariable Long id, User user) {
        userService.updateUser(id, user);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public void deleteUserById(@PathVariable Long id) {
        userService.deleteUserById(id);
    }
}

github/springboot-api下载本例的源代码

作者: Ashish Lahoti
原文:https://codingnconcepts.com/spring-boot/build-restful-api-with-spring-boot/

李白
关注 私信
文章
12
关注
0
粉丝
0