简体   繁体   English

使用 Spring 在 java 中为 RESTful API 创建端点的最佳方法

[英]Best approach to creating endpoints for a RESTful API in java using Spring

I'm new to the field, trying to create an API using Spring with Maven dependencies such as Project Lombok, just to get more hands on with my learning.我是该领域的新手,尝试使用 Spring 和 Maven 依赖项(例如 Project Lombok)创建 API,以便更多地了解我的学习。

So i've managed to write some code to start the application and now i'm creating some endpoints.所以我设法编写了一些代码来启动应用程序,现在我正在创建一些端点。 The first of them was a "list users" type of thing that my brother helped me with, it's divided in 3 classes that i'll list below:其中第一个是我兄弟帮助我完成的“列表用户”类型的事情,它分为 3 个类别,我将在下面列出:

(1) UserListResponse.java: (1) 用户列表响应.java:

package com.tropicalia.meu_cardapio.api.user.list;

import lombok.Data;

@Data
public class UserListResponse {

    private Long id;

    private String name;

    private String email;

}

(2) UserListRest.java (2) UserListRest.java

package com.tropicalia.meu_cardapio.api.user.list;

import com.tropicalia.meu_cardapio.domain.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

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

    @Autowired
    UserListService service;

    @GetMapping
    public ResponseEntity<List<User>> list() {
        return ResponseEntity.ok().body(service.listUsers());
    }
}

(3) UserListService.java (3) 用户列表服务.java

package com.tropicalia.meu_cardapio.api.user.list;

import com.tropicalia.meu_cardapio.domain.user.User;
import com.tropicalia.meu_cardapio.domain.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserListService {

    @Autowired
    UserRepository repository;

    public List<User> listUsers() {
        List<User> list = repository.findAll();
        return list;
    }
}

The reason i'm writing this post is that i do not know how to create the other endpoints such as "create user" and i don't even know where to start with my research, would be very grateful if someone could help me with some guidance here.我写这篇文章的原因是我不知道如何创建其他端点,例如“创建用户”,我什至不知道从哪里开始我的研究,如果有人能帮助我,我将不胜感激这里有一些指导。

One of the approaches I use is to group controller in so-called resources, like:我使用的一种方法是将 controller 分组到所谓的资源中,例如:

  • User Resource用户资源
  • Book Resource etc图书资源等

Then you may create one controller, called UserController with mapping on controller level, and some specific mappings in method level like:然后您可以创建一个 controller,称为UserController ,在 controller 级别上进行映射,并在方法级别上创建一些特定映射,例如:

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

    @GetMapping
    public ResponseEntity<List<UserDto>> getUsers(){}

    @GetMapping("/{id}")
    public ResponseEntity<UserDto> getOneUser(@PathVariable Long id){}

    @PostMapping
    public ResponseEntity<UserDto> addUser(@RequestBody UserDto user){}

    @PutMapping("/{id}")
    public ResponseEntity<UserDto> updateUser(@PathVariable Long id, @RequestBody UserDto user){}

}

Then you can use the service/repository layer with spring data JPA to read/persist your data.然后,您可以使用带有 spring 数据 JPA 的服务/存储库层来读取/保存您的数据。 The good starting points are spring guides like:好的起点是 spring 指南,例如:

First of all, maybe is better just define more generic endpoints and not UserList, usually is better just define the User endpoint and add there all methods and routes like listUsers or getUser, addUser...首先,最好只定义更多通用端点而不是UserList,通常最好只定义用户端点并在那里添加所有方法和路由,如listUsers或getUser,addUser ...

Furthermore when you use @Repository it generates the basic methods to "get add delete or update" your object.此外,当您使用@Repository 时,它会生成基本方法来“获取添加删除或更新”您的 object。

For example you can define inside your Service例如,您可以在 Service 中定义

public User saveUser(User user) {
    if (user != null) {
        return repository.save(user);
    } else {
        return null;
    }
}

And in your Controller:在您的 Controller 中:

@PostMapping("/addUser")
public User addUser(@Valid @RequestBody User user) {

    user newUser = service.saveUser(user);

    return newUser;
}

Tell me if you have more doubts.如果您有更多疑问,请告诉我。 :D :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM