【发布时间】:2016-05-26 14:45:36
【问题描述】:
我使用 Spring Initializr (https://start.spring.io/) 创建了一个只有启动器“Jersey (JAX-RS)”和“HATEOAS”的应用程序。 然后我添加了@EnableHypermediaSupport(type = HAL),但我无法以 HAL 格式正确呈现链接。
我的目标格式:
{
"name": "Hello",
"count": 42,
"_links": {
"self": {
"href": "http://localhost:8080/api/foo"
}
}
}
我目前得到的是:
{
"name": "Hello",
"count": 42,
"links": [
{
"rel": "self",
"href": "http://localhost:8080/api/foo"
}
]
}
除了initializr生成的类之外,我添加了这个配置
@Configuration
@ApplicationPath("api")
@Component
@EnableHypermediaSupport(type = HAL)
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
registerEndpoints();
}
private void registerEndpoints() {
register(FooResource.class);
}
}
此资源(端点):
@Component
@Path("foo")
public class FooResource {
@GET
@Produces(MediaTypes.HAL_JSON_VALUE)
public Resource<Foo> getFoo() {
final Resource<Foo> fooTo = new Resource<>(new Foo("Hello", 42));
fooTo.add(JaxRsLinkBuilder.linkTo(FooResource.class).withRel("self"));
return fooTo;
}
}
还有一个虚拟豆子:
public class Foo {
private String name;
private int count;
public Foo() {
}
public Foo(String name, int count) {
this.name = name;
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
我也试过添加
@EnableHypermediaSupport(type = HAL)
在应用程序类上的@SpringBootApplication 旁边。
当我
GET localhost:8080/api/foo
我收到内容类型正确的响应
application/hal+json;charset=UTF-8
但格式仍然错误(“链接”属性作为数组而不是“_links”属性作为对象/映射)。
【问题讨论】:
标签: java spring-boot jersey spring-hateoas