我正在尝试使用Spring HATEOAS构建符合HAL的REST API。
经过一番摆弄后,我设法像预期的那样开始 工作。 (样本)输出现在看起来像这样:
{
"_links": {
"self": {
"href": "http://localhost:8080/sybil/configuration/bricks"
}
},
"_embedded": {
"brickDomainList": [
{
"hostname": "localhost",
"port": 4223,
"_links": {
"self": {
"href": "http://localhost:8080/sybil/configuration/bricks/localhost"
}
}
},
{
"hostname": "synerforge001",
"port": 4223,
"_links": {
"self": {
"href": "http://localhost:8080/sybil/configuration/bricks/synerforge001"
}
}
}
]
}
}
我不喜欢" brickDomainList"数组的名称。它应该说"砖",理想情况下。我该怎么改变它?
这是产生输出的控制器:
@RestController
@RequestMapping("/configuration/bricks")
public class ConfigurationBricksController {
private BrickRepository brickRepository;
private GraphDatabaseService graphDatabaseService;
@Autowired
public ConfigurationBricksController(BrickRepository brickRepository, GraphDatabaseService graphDatabaseService) {
this.brickRepository = brickRepository;
this.graphDatabaseService = graphDatabaseService;
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET, produces = "application/hal+json")
public Resources<BrickResource> bricks() {
List<BrickDomain> bricks;
List<BrickResource> resources = new ArrayList<>();
List<Link> links = new ArrayList<>();
Link self = linkTo(ConfigurationBricksController.class).withSelfRel();
links.add(self);
try(Transaction tx = graphDatabaseService.beginTx()) { // begin transaction
// get all Bricks from database and cast them into a list so that they're actually fetched
bricks = new ArrayList<>(IteratorUtil.asCollection(brickRepository.findAll()));
// end transaction
tx.success();
}
for (BrickDomain brick : bricks) {
self = linkTo(methodOn(ConfigurationBricksController.class).brick(brick.getHostname())).withSelfRel();
BrickResource resource = new BrickResource(brick, self);
resources.add(resource);
}
return new Resources<>(resources, links);
}
}
是否有一些注释或我可以添加的内容来更改数组的名称?
如果您想/需要查看BrickResource类或存储库或其他内容:https://github.com/ttheuer/sybil/tree/mvctest/src/main/java/org/synyx/sybil
BrickResource位于api / resources /中,存储库位于数据库/中,而域名中的BrickDomain位于/。
谢谢!
答案 0 :(得分:14)
只需使用Evo Inflector即可。如果您有Maven项目,则添加依赖项
<dependency>
<groupId>org.atteo</groupId>
<artifactId>evo-inflector</artifactId>
<version>1.2</version>
</dependency>
或者您可以将@Relation(collectionRelation = "bricks")
添加到BrickDomain
类
@Relation(collectionRelation = "bricks")
public class BrickDomain { … }