基本路径未出现在ResourceProcessor自定义链接中

时间:2015-10-13 00:48:45

标签: java spring spring-data-rest spring-hateoas

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

  ...
}

}

我还需要做些什么才能让基本路径出现在链接中?

1 个答案:

答案 0 :(得分:1)

我想它与错误ControllerLinkBuilder does not take Spring Data REST's base path into accountCustom 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())