我正在使用 Spring Boot 和 HATEOAS 来构建一个 REST API,我正在为居里创建而苦苦挣扎。Spring HATEOAS 指南说,为了在响应中自动插入居里,您应该执行以下操作:
@Configuration
@EnableWebMvc
@EnableHypermediaSupport(type= {HypermediaType.HAL})
public class Config {
@Bean
public CurieProvider curieProvider() {
return new DefaultCurieProvider("ex", new UriTemplate("http://www.example.com{#rel}"));
}
}
我的配置类是这样的:
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
@Bean
public CurieProvider curieProvider() {
return new DefaultCurieProvider("xpto", new UriTemplate("http://www.xpto.com{#rel}"));
}
}
我尝试将@EnableWebMvc 添加到我的配置类中,但它改变了响应的呈现(hal)并且居里不出现。我必须在控制器上做些什么来创建居里?
更新: 我更新了 Spring Hateoas(到 0.17.0.RELEASE),现在我的集合名称用居里呈现,但居里没有出现在 _links 部分:
{
"_links": {
"self": {
"href": "http://localhost:8080/technologies"
}
},
"_embedded": {
"mycurie:technology": [
{
"id": 1,
"description": "A",
"_links": {
"self": {
"href": "http://localhost:8080/technologies/1"
}
}
},
{
"id": 2,
"description": "B",
"_links": {
"self": {
"href": "http://localhost:8080/technologies/2"
}
}
}
]
}
}
如果我在 _links 部分添加一个链接,则会出现居里链接:
{
"_links": {
"self": {
"href": "http://localhost:8080/technologies"
},
"mycurie:xpto": {
"href": "http://localhost:8080/xpto"
},
"curies": [
{
"href": "http://localhost:8080/rels/{rel}",
"name": "mycurie",
"templated": true
}
]
},
"_embedded": {
"mycurie:technology": [
{
"id": 1,
"description": "A",
"_links": {
"self": {
"href": "http://localhost:8080/technologies/1"
}
}
},
{
"id": 2,
"description": "B",
"_links": {
"self": {
"href": "http://localhost:8080/technologies/2"
}
}
}
]
}
}
这是我的控制器:
@RestController
@ExposesResourceFor(Technology.class)
@RequestMapping(value = "/technologies")
public class TechnologyRestController {
...
@RequestMapping(method = RequestMethod.GET, produces = "application/vnd.xpto-technologies.text+json")
public Resources<TechnologyResource> getAllTechnologies() {
List<Technology> technologies = technologyGateway.getAllTechnologies();
Resources<TechnologyResource> technologiesResources = new Resources<TechnologyResource>(technologyResourceAssembler.toResources(technologies));
technologiesResources.add(linkTo(methodOn(TechnologyRestController.class).getAllTechnologies()).withSelfRel());
return technologiesResources;
}
}