dan*_*niu 12 java spring spring-hateoas spring-boot
我正在关注Spring REST的教程,并试图将HATEOAS链接添加到我的Controller结果中.
我有一个简单的User类和一个CRUD控制器.
class User {
private int id;
private String name;
private LocalDate birthdate;
// and getters/setters
}
Run Code Online (Sandbox Code Playgroud)
服务:
@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
}
Run Code Online (Sandbox Code Playgroud)
一切正常,除了我的控制器,我想从所有用户列表添加链接到单个用户:
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();
}
Run Code Online (Sandbox Code Playgroud)
这样,对于结果列表中的每个用户,都会添加一个指向用户自身的链接.
链接本身创建正常,但生成的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
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
哪里有空值(字段hreflang,media等等)都来自他们为什么加入?有办法摆脱它们吗?
在构建指向所有用户列表的链接时,它们不会出现:
@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);
}
Run Code Online (Sandbox Code Playgroud)
如果有其他人偶然发现这个并且我想出来的话还有进一步的参考:我添加了一个条目application.properties,即
spring.jackson.default-property-inclusion=NON_NULL
Run Code Online (Sandbox Code Playgroud)
为什么这对于Link物体是必要的,但不是User我不知道的(并且没有更深入地倾斜).
| 归档时间: |
|
| 查看次数: |
3996 次 |
| 最近记录: |