【发布时间】:2015-11-02 09:31:54
【问题描述】:
我正在尝试使用 Spring hateoas 来解析从抽象控制器继承的端点的 URL。
我认为先给出代码会使问题更容易理解。
这是我的抽象控制器:
package com.stackoverflow.question.spring.rest.controllers;
import org.springframework.hateoas.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
public class AbstractController {
@RequestMapping(value="/cat", method=RequestMethod.GET)
public Resource<String> cat() {
return new Resource<>("cat");
}
}
这是我使用 methodOn 的控制器:
package com.stackoverflow.question.spring.rest.controllers;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import org.springframework.hateoas.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/test", produces = { "application/json; charset=utf-8" })
public class TestController extends AbstractController {
@RequestMapping(method = RequestMethod.GET)
public Resource<String> test() {
return new Resource<>("test", linkTo(
methodOn(TestController.class).cat()).withRel("cat"), linkTo(
methodOn(TestController.class).uglyfix()).withRel("uglyfix"));
}
@RequestMapping(value = "/uglyfix", method = RequestMethod.GET)
public Resource<String> uglyfix() {
return new Resource<>("ugly fix", linkTo(TestController.class).slash(
"cat").withRel("cat"));
}
}
这是我去 /resources/test 时得到的:
{
"content": "test",
"links": [
{
"rel": "cat",
"href": "http://localhost:8080/resources/cat"
},
{
"rel": "uglyfix",
"href": "http://localhost:8080/resources/test/uglyfix"
}
]
}
这就是我所期望的,也是我希望 hatoas 做的:
{
"content": "test",
"links": [
{
"rel": "cat",
"href": "http://localhost:8080/resources/test/cat"
},
{
"rel": "uglyfix",
"href": "http://localhost:8080/resources/test/uglyfix"
}
]
}
当然,我可以做我在端点uglyfix中所做的事情,但我不喜欢这个解决方案,因为这意味着如果我在我的抽象控制器中更改我的请求映射,我将不得不更改我的TestController的代码。
也许在我的抽象控制器顶部添加 @RequestMapping(value="test") 可以解决我的问题,但我也不想要这个解决方案,因为我想将我的扩展抽象控制器与多个控制器一起使用。
有什么干净的方法吗,我期望什么?
【问题讨论】:
标签: java spring inheritance hateoas spring-hateoas