Java – use spring data rest to expose hypermedia links on collections, even if they are empty
First, I read the previous question: exposing link on collection entity in spring data rest
But the problem still exists, there is no trick
In fact, if I want to expose a link to a collection resource, I'm using the following code:
@Component public class FooProcessor implements ResourceProcessor<PagedResources<Resource<Foo>>> { private final FooLinks fooLinks; @Inject public FooProcessor(FooLinks fooLinks) { this.FooLinks = fooLinks; } @Override public PagedResources<Resource<Foo>> process(PagedResources<Resource<Foo>> resource) { resource.add(fooLinks.getMyCustomLink()); return resource; } }
This is normal unless the collection is empty
The only feasible method is to replace the following code with:
@Component public class FooProcessor implements ResourceProcessor<PagedResources> { private final FooLinks fooLinks; @Inject public FooProcessor(FooLinks fooLinks) { this.FooLinks = fooLinks; } @Override public PagedResources process(PagedResources resource) { resource.add(fooLinks.getMyCustomLink()); return resource; } }
But by doing so, the link will be exposed to all collections
I can create conditions to expose only what I want, but I don't think it's clean
Solution
I think spring has some magic when trying to find the type of collection - you can't tell what type it is on an empty collection - so spring data rest can't determine which resourceprocessor to use
I think I've seen org springframework. data. rest. webmvc. ResourceProcessorHandlerMethodReturnValueHandler. Resourcesprocessorwrapper #isvaluetypematch they try to determine the type by looking at the first element in the collection, otherwise they just stop processing:
if (content.isEmpty()) { return false; }
So I don't think you can use spring data rest to solve this problem For your controller, you can go back and write a custom controller and use spring HATEOAS and implement your own resourceassemblysupport to view links on empty collections