Can I make a custom controller mirror the formatting of Spring-Data-Rest / Spring-Hateoas generated classes?

I’ve found a way to imitate the behavior of Spring Data Rest completely. The trick lies in using a combination of the PagedResourcesAssembler and an argument-injected instance of PersistentEntityResourceAssembler. Simply define your controller as follows…

@RepositoryRestController
@RequestMapping("...")
public class ThingController {

    @Autowired
    private PagedResourcesAssembler pagedResourcesAssembler;

    @SuppressWarnings("unchecked") // optional - ignores warning on return statement below...
    @RequestMapping(value = "...", method = RequestMethod.GET)
    @ResponseBody
    public PagedResources<PersistentEntityResource> customMethod(
            ...,
            Pageable pageable,
            // this gets automatically injected by Spring...
            PersistentEntityResourceAssembler resourceAssembler) {

        Page<MyEntity> page = ...;
        ...
        return pagedResourcesAssembler.toResource(page, resourceAssembler);
    }
}

This works thanks to the existence of PersistentEntityResourceAssemblerArgumentResolver, which Spring uses to inject the PersistentEntityResourceAssembler for you. The result is exactly what you’d expect from one of your repository query methods!

Leave a Comment