我正在尝试覆盖 API 的默认 GET 动词以添加一些更具体的详细信息。
我创建了一个restController和一个Get requestMapping:
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Resources<User>> getUsers(Pageable pageable) {
Page<User> users = userReposiotry.findAll(pageable);
Resources<User> userResources = new Resources<>(users);
return new ResponseEntity<Resources<User>>(userResources, HttpStatus.OK);
}
它工作得很好,但它不会返回链接和其他在不覆盖的情况下可用的附加信息。
自定义返回:
{
"_embedded": {
"users": [
{
"id": 1,
"username": "admin",
"registrationDate": "2015-11-18T21:04:54.000+0000",
"name": "Admin",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b4a4f4642456b4a4f46424505484446" rel="noreferrer noopener nofollow">[email protected]</a>",
"enabled": true,
"dateOfBirth": "2015-11-18",
"imageIdentifier": null,
"confirmationKey": ""
}]
}
}
而原文:
{
"_embedded": {
"users": [
{
"id": 1,
"username": "admin",
"registrationDate": "2015-11-18T21:04:54.000+0000",
"name": "Admin",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cfdf8f1f5f2dcfdf8f1f5f2b2fff3f1" rel="noreferrer noopener nofollow">[email protected]</a>",
"enabled": true,
"dateOfBirth": "2015-11-18",
"imageIdentifier": null,
"confirmationKey": "",
"_links": {
"self": [
{
"href": "http://localhost:8080/api/users/1"
},
{
"href": "http://localhost:8080/api/users"
}
],
"user": {
"href": "http://localhost:8080/api/users/1{?projection}",
"templated": true
},
"inviteToApps": {
"href": "http://localhost:8080/api/users/1/inviteToApps"
},
"userRoles": {
"href": "http://localhost:8080/api/users/1/userRoles"
},
"currencyTokens": {
"href": "http://localhost:8080/api/users/1/currencyTokens"
},
"workoutAttendees": {
"href": "http://localhost:8080/api/users/1/workoutAttendees"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/users"
},
"profile": {
"href": "http://localhost:8080/api/profile/users"
},
"search": {
"href": "http://localhost:8080/api/users/search"
}
},
"page": {
"size": 20,
"totalElements": 7,
"totalPages": 1,
"number": 0
}
}
如何像原来那样将关系添加到自定义关系?
最佳答案
只需返回自定义 Bean、Map 等,而不是 ResponseEntity:
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
public Object getUsers(Pageable pageable) {
Page<User> users = userReposiotry.findAll(pageable);
Resources<User> userResources = new Resources<>(users);
List<MyCustomUser> customUsers = [...]
return customUSers;
}
// "some more specific details" in MyCustomUser
public class MyCustomUser extends User{
private List<Links> links;
// TODO: constructor, getter, setter.
}
关于java - Spring Data Rest 重写默认 GET 动词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34968149/