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

后端 未结 3 1409
独厮守ぢ
独厮守ぢ 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 20:58

    I believe I've solved this problem in a fairly straightforward way, although it could have been better documented.

    After reading the implementation of SimplePagedResourceAssembler I realized a hybrid solution might work. The provided Resource class renders entities correctly, but doesn't include links, so all you need to do is add them.

    My QuestionResourceAssembler implementation looks like this:

    @Component
    public class QuestionResourceAssembler implements ResourceAssembler> {
    
        @Autowired EntityLinks entityLinks;
    
        @Override
        public Resource toResource(Question question) {
            Resource resource = new Resource(question);
    
            final LinkBuilder lb = 
                entityLinks.linkForSingleResource(Question.class, question.getId());
    
            resource.add(lb.withSelfRel());
            resource.add(lb.slash("answers").withRel("answers"));
            // other links
    
            return resource;
        }
    }
    

    Once that's done, in my controller I used Option 2 above:

        return pagedResourcesAssembler.toResource(page, questionResourceAssembler);
    

    This works well, and isn't too much code. The only hassle is you need to manually add links for each reference you need.

提交回复
热议问题