Providing collection hyperlink links, even empty ones using Spring Data Rest

First, I read the previous question: Disclosing a reference to a collection object in spring REST data

But the problem still persists without a trick.

Indeed, if I want to open a link for collection resources, I use 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 works correctly, unless the collection is empty ...

The only way to work is to replace my 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 at the same time, the link will be displayed for all collections.

I can create a condition for setting only what I want, but I do not think that it is clean.

+7
java spring spring-data-rest spring-hateoas
source share
1 answer

I think spring does some magic there, trying to detect the type of collection - in an empty collection you cannot determine which type it belongs to, so spring-data-rest cannot determine which ResourceProcessor to use.

I think I saw in org.springframework.data.rest.webmvc.ResourceProcessorHandlerMethodReturnValueHandler.ResourcesProcessorWrapper#isValueTypeMatch that they are trying to determine the type by looking at the first item in the collection and otherwise just stop processing:

 if (content.isEmpty()) { return false; } 

So, I think you cannot solve this problem using spring -data-rest. For your controller, you can go back to writing a custom controller and use spring hateoas and implement your own ResourceAssemblerSupport to see a link to empty collections.

+2
source share

All Articles