我正在尝试将HATEOAS与Spring HATEOAS一起使用,并且需要使用Spring HATEOAS将enum
s作为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 ResourcefruitsWithResource() { Resource resource = new Resource (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 fruitsWithResources() { Resources resources = new Resources (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 ResourceProcessorrepositoryLinksResourceProcessor() { return new ResourceProcessor () { @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
)看起来很容易获得枚举,但我不确定这是一个正确的方法.