如何在Spring Data REST中添加指向root资源的链接?

问题描述 投票:12回答:2

如何在Spring Data REST资源的根列表中公开外部资源(不通过存储库管理)?我在Restbucks中按照模式定义了一个控制器

spring-data-rest
2个回答
19
投票

这可以通过实施ResourceProcessor<RepositoryLinksResource>来完成。

以下代码段将“/ others”添加到根列表中

@Controller
@ExposesResourceFor(Other.class)
@RequestMapping("/others")
public class CustomRootController implements
        ResourceProcessor<RepositoryLinksResource> {

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<Resources<Resource<Other>>> listEntities(
            Pageable pageable) throws ResourceNotFoundException {
            //... do what needs to be done
    }

    @Override
    public RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add(ControllerLinkBuilder.linkTo(CustomRootController.class).withRel("others"));

        return resource;
    }
}

应该添加

{
    "rel": "others",
    "href": "http://localhost:8080/api/others"
}

到您的根列表链接


1
投票

我一直在寻找同一问题的答案,但关键是:我没有控制器。我的网址指向在auth过滤器中创建的内容。对我有用的是创建一个没有任何方法的RootController,并用它来构建ResourceProcessor实现中的链接。

@RestController
@RequestMapping("/")
public class RootController {}

然后使用空控制器插入链接。

@Component
public class AuthLinkProcessor implements ResourceProcessor<RepositoryLinksResource> {

    @Override
    public RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add(
                linkTo(RootController.class)
                .slash("auth/login")
                .withRel("auth-login"));
        return resource;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.