Charlie
Charlie

Reputation: 3374

How to define a bean for PersistentEntityResourceAssembler?

When I try to autowire PersistentEntityResourceAssembler in my custom controller it gives me the following error.

Description:

Field resourceAssembler in api.controller.IslandController required a bean of type 'org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler' in your configuration.

Here is my controller implementation:

@RestController
public class IslandController {

    @Autowired
    private IslandRepository islandRepo;

    @Autowired
    private PagedResourcesAssembler pagedResourcesAssembler;

    @Autowired
    private PersistentEntityResourceAssembler resourceAssembler;

    @RequestMapping(method = GET, value = "islands")
    public ResponseEntity<?> getAllIslands(Pageable page) {
        Page<Island> islandList = islandRepo.findAll(page);
        return new ResponseEntity<>(pagedResourcesAssembler.toResource(islandList, resourceAssembler), HttpStatus.OK);
    }

So how do I define a bean for PersistentEntityResourceAssembler?

Upvotes: 0

Views: 716

Answers (1)

Marc Tarin
Marc Tarin

Reputation: 3169

This is not the way to solve this problem : get rid of the @Autowired PersistentEntityResourceAssembler and pass a PersistentEntityResourceAssembler parameter to your method instead, and let Spring do its magic

@RequestMapping(method = GET, value = "islands")
public ResponseEntity<?> getAllIslands(Pageable page,
        PersistentEntityResourceAssembler resourceAssembler) {
    Page<Island> islandList = islandRepo.findAll(page);

    return new ResponseEntity<>(pagedResourcesAssembler.toResource(islandList, resourceAssembler), HttpStatus.OK);
}

Upvotes: 2

Related Questions