基本路径未显示在资源处理器自定义链接中



在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"
  },
  ...
}

}

还有什么我需要做得到的基本路径出现在链接?

我想它与bug ControllerLinkBuilder不考虑Spring Data REST的基本路径和自定义控制器+更改的基本路径不显示在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())

最新更新