在Spring Data REST中,我使用ResourceProcessor
:
@Component
public class ServiceInstanceProcessor
implements ResourceProcessor<Resource<ServiceInstance>> {
@Override
public Resource<ServiceInstance> process(Resource<ServiceInstance> resource) {
Long id = resource.getContent().getId();
ServiceInstanceController controller =
methodOn(ServiceInstanceController.class);
resource.add(linkTo(controller.getNodeSummary(id))
.withRel("nodeSummary"));
resource.add(linkTo(controller.getHealthBreakdown(id))
.withRel("healthBreakdown"));
resource.add(linkTo(controller.getRotationBreakdown(id))
.withRel("rotationBreakdown"));
return resource;
}
}
但是,生成的链接不包括基本路径,即使我已将控制器标记为@BasePathAwareController
,即使默认链接包含基本路径:
{
...
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/serviceInstances/101"
},
"serviceInstance" : {
"href" : "http://localhost:8080/api/serviceInstances/101{?projection}",
"templated" : true
},
"nodeSummary" : {
"href" : "http://localhost:8080/serviceInstances/101/nodeSummary"
},
"healthBreakdown" : {
"href" : "http://localhost:8080/serviceInstances/101/healthBreakdown"
},
"rotationBreakdown" : {
"href" : "http://localhost:8080/serviceInstances/101/rotationBreakdown"
},
...
}
}
我还需要做些什么才能让基本路径出现在链接中?
答案 0 :(得分:1)
我想它与错误ControllerLinkBuilder does not take Spring Data REST's base path into account和Custom Controller + changed base path doesn't show up in HAL
有关作为解决方法,我接下来要做:
@Autowired
private final RepositoryRestConfiguration config;
private Link fixLinkSelf(Object invocationValue) {
return fixLinkTo(invocationValue).withSelfRel();
}
@SneakyThrows
private Link fixLinkTo(Object invocationValue) {
UriComponentsBuilder uriComponentsBuilder = linkTo(invocationValue).toUriComponentsBuilder();
URL url = new URL(uriComponentsBuilder.toUriString());
uriComponentsBuilder.replacePath(config.getBasePath() + url.getPath());
return new Link(uriComponentsBuilder.toUriString());
}
用法与linkTo
相同:
resources.add(fixLinkSelf(methodOn(VoteController.class).history()));
resources.add(fixLinkTo(methodOn(VoteController.class).current()).withRel("current"));
基于带有addPath的当前请求的简单案例的其他解决方法:
new Link(ServletUriComponentsBuilder.fromCurrentRequest().path(addPath).build().toUriString())