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

3
在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个回答

1
我想这与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())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接