【发布时间】:2016-04-02 02:03:58
【问题描述】:
我正在尝试将 HATEOAS 与 Spring HATEOAS 一起使用,并且需要通过 Spring HATEOAS 将 enums 公开为 REST API。
我尝试了以下三种方式:
@RestController
@RequestMapping(path = "/fruits")
public class FruitResourceController {
@RequestMapping(method = RequestMethod.GET)
public Fruit[] fruits() {
return Fruit.values();
}
// NOTE: The `produces` attribute is only for browsers.
@RequestMapping(path = "/with-resource", method = RequestMethod.GET,
produces = MediaTypes.HAL_JSON_VALUE)
public Resource<Fruit[]> fruitsWithResource() {
Resource<Fruit[]> resource = new Resource<Fruit[]>(Fruit.values());
Link selfLink = linkTo(methodOn(FruitResourceController.class).fruitsWithResource())
.withSelfRel();
resource.add(selfLink);
return resource;
}
// NOTE: The `produces` attribute is only for browsers.
@RequestMapping(path = "/with-resources", method = RequestMethod.GET,
produces = MediaTypes.HAL_JSON_VALUE)
public Resources<Fruit> fruitsWithResources() {
Resources<Fruit> resources = new Resources<Fruit>(Arrays.asList(Fruit.values()));
Link selfLink = linkTo(methodOn(FruitResourceController.class).fruitsWithResources())
.withSelfRel();
resources.add(selfLink);
return resources;
}
}
但我不知道哪种方法适合 HATEOAS。任何建议或参考将不胜感激。
作为参考,我有以下 Spring Data REST 配置:
@Configuration
public class SpringDataRestConfig {
@Bean
public ResourceProcessor<RepositoryLinksResource> repositoryLinksResourceProcessor() {
return new ResourceProcessor<RepositoryLinksResource>() {
@Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
Link fruitsLink = linkTo(methodOn(FruitResourceController.class).fruitsWithResources())
.withRel("fruits");
resource.add(fruitsLink);
return resource;
}
};
}
}
请参阅以下示例项目:
https://github.com/izeye/spring-boot-throwaway-branches/blob/data-jpa-and-rest/src/main/java/com/izeye/throwaway/SpringDataRestConfig.java https://github.com/izeye/spring-boot-throwaway-branches/blob/data-jpa-and-rest/src/main/java/com/izeye/throwaway/FruitResourceController.java
--- 更新于 2016.01.04
使用 ALPS (/profile) 获得枚举列表看起来不错,但我不确定这是一种正确的方法。
【问题讨论】:
-
“
produces属性仅适用于浏览器” - 你认为它是为什么呢? -
@zeroflagL 对不起,令人困惑的评论。这意味着它只存在于浏览器强制呈现为 JSON,并不意味着它只影响浏览器。
-
expsing
enums 到底是什么意思?你想公开一个静态的、只读的字符串值列表吗?那你为什么不干脆那样做呢?只需在 REST 控制器中返回枚举本身 Fruit.values() 即可。 Spring 会自动将 HTTP 响应到一个字符串数组。 -
关于 HATEOAS:这只是表示的一种格式(带有链接、href 和资源)您希望将哪些链接添加到您的枚举值中?你能做到吗?但是为了什么?据我了解,这只是一个静态的字符串列表。没有 POST 到那个休息端点或者有吗?
-
为什么这么多赞?!
标签: rest spring-data-rest hateoas spring-hateoas