Defining a resource assembler for a REST Spring HATEOAS controller

前端 未结 1 1894
死守一世寂寞
死守一世寂寞 2021-02-14 07:01

I\'m trying to add HATEOAS links to a JSON resource served by a Spring REST controller.

I see I should use a resource assembler as described at https://github.com/spring

相关标签:
1条回答
  • 2021-02-14 07:42

    Your ResourceAssembler implementation needs to know about both the data domain class and the REST domain class, because its job is to convert the former to the latter.

    If you want to keep knowledge of your data classes out of your controller, you could make a resource conversion service which would retrieve the data from the repo and use a ResourceAssembler to turn it into resources that the controller can know about.

    @Component
    public class AdminResourceAssembler extends ResourceAssemblerSupport<Admin, AdminResource> {
        public AdminResourceAssembler() {
            super(AdminController.class, AdminResource.class);
        }
    
        public AdminResource toResource(Admin admin) {
            AdminResource adminResource = createResourceWithId(admin.getId(), admin); // adds a "self" link
            // TODO: copy properties from admin to adminResource
            return adminResource;
        }
    }
    
    @Service
    public class AdminResourceService {
        @Inject private AdminRepository adminRepository;
        @Inject private AdminResourceAssembler adminResourceAssembler;
    
        @Transactional
        public AdminResource findOne(Long adminId) {
            Admin admin = adminRepository.findOne(adminId);
            AdminResource adminResource = adminResourceAssembler.toResource(admin);
            return adminResource;
        }
    }
    
    @Controller
    @RequestMapping("/admins")
    public class AdminController {
        @Inject private AdminResourceService adminResourceService;
    
        @RequestMapping(value="/{adminId}", method=RequestMethod.GET)
        public HttpEntity<AdminResource> findOne(@PathVariable("adminId") Long adminId) {
            AdminResource adminResource = adminResourceService.findOne(adminId);
            return new ReponseEntity<>(adminResource, HttpStatus.OK);
        }
    }
    
    0 讨论(0)
提交回复
热议问题