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

后端 未结 3 1408
独厮守ぢ
独厮守ぢ 2020-11-29 20:29

I\'m trying to do something I think should be really simple. I have a Question object, setup with spring-boot, spring-data-rest and spring-hateoas. All the basi

3条回答
  •  半阙折子戏
    2020-11-29 21:22

    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 customMethod(
                ...,
                Pageable pageable,
                // this gets automatically injected by Spring...
                PersistentEntityResourceAssembler resourceAssembler) {
    
            Page 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!

提交回复
热议问题