草庐IT

java - Spring Hateoas ControllerLinkBuilder 添加空字段

coder 2024-03-06 原文

我正在学习有关 Spring REST 的教程,并尝试将 HATEOAS 链接添加到我的 Controller 结果中。

我有一个简单的用户类和一个 CRUD Controller 。

class User {
    private int id;
    private String name;
    private LocalDate birthdate;
    // and getters/setters
}

服务:

@Component
class UserService {
    private static List<User> users = new ArrayList<>();
    List<User> findAll() {
        return Collections.unmodifiableList(users);
    }
    public Optional<User> findById(int id) {
        return users.stream().filter(u -> u.getId() == id).findFirst();
    }
    // and add and delete methods of course, but not important here
}

一切正常,除了在我的 Controller 中,我想将所有用户列表中的链接添加到单个用户:

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/users")
    public List<Resource<User>> getAllUsers() {
        List<Resource<User>> userResources = userService.findAll().stream()
            .map(u -> new Resource<>(u, linkToSingleUser(u)))
            .collect(Collectors.toList());
        return userResources;
    }
    Link linkToSingleUser(User user) {
        return linkTo(methodOn(UserController.class)
                      .getById(user.getId()))
                      .withSelfRel();
    }

这样对于结果列表中的每个用户,都会添加指向用户本身的链接。

链接本身创建的很好,但是生成的 JSON 中有多余的条目:

[
    {
        "id": 1,
        "name": "Adam",
        "birthdate": "2018-04-02",
        "links": [
            {
                "rel": "self",
                "href": "http://localhost:8080/users/1",
                "hreflang": null,
                "media": null,
                "title": null,
                "type": null,
                "deprecation": null
            }
        ]
    }
]

空值字段(hreflangmedia等)是从哪里来的,为什么要添加?有没有办法摆脱它们?

在建立指向所有用户列表的链接时它们不会出现:

@GetMapping("/users/{id}")
public Resource<User> getById(@PathVariable("id") int id) {
    final User user = userService.findById(id)
                                 .orElseThrow(() -> new UserNotFoundException(id));
    Link linkToAll = linkTo(methodOn(UserController.class)
                            .getAllUsers())
                            .withRel("all-users");
    return new Resource<User>(user, linkToAll);
}

最佳答案

为了进一步引用,以防其他人偶然发现这一点,我想通了:我在 application.properties 中添加了一个条目,即

spring.jackson.default-property-inclusion=NON_NULL

为什么这对 Link 对象是必需的,但对 User 不是必需的,我不知道(也没有深入研究)。

关于java - Spring Hateoas ControllerLinkBuilder 添加空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49615358/

有关java - Spring Hateoas ControllerLinkBuilder 添加空字段的更多相关文章

随机推荐