我正在尝试使用 Spring hateoas 来解析从抽象 Controller 继承的端点的 URL。
我认为先给出代码会让问题更容易理解。
这是我的抽象 Controller :
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 的 Controller :
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"
}
]
}
这就是我所期望的,也是我希望 hateoas 做的:
{
"content": "test",
"links": [
{
"rel": "cat",
"href": "http://localhost:8080/resources/test/cat"
},
{
"rel": "uglyfix",
"href": "http://localhost:8080/resources/test/uglyfix"
}
]
}
当然,我可以像在端点 uglyfix 中那样做,但我不喜欢这个解决方案,因为这意味着如果我在我的抽象 Controller 中更改请求映射,我将不得不更改我的 TestController 的代码。
也许在我的抽象 Controller 的顶部添加 @RequestMapping(value="test") 会解决我的问题,但我也不想要这个解决方案,因为我想将我的抽象 Controller 扩展与多个 Controller 一起使用。
是否有一种干净的方式来做我所期望的?
最佳答案
我觉得有点愚蠢,因为我只是将 Spring hateoas 从 0.9.0.RELEASE 迁移到 0.17.0.RELEASE,它解决了我的问题。
关于java - 带有继承方法的Spring hateoas methodOn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31920060/