Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Rest Custom Links on Resource

The Spring Data Rest repository notes that Custom Links can be added to an Entity as below:

http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_the_resourceprocessor_interface

Example Given:

@Bean
public ResourceProcessor<Resource<Person>> personProcessor() {

   return new ResourceProcessor<Resource<Person>>() {

     @Override
     public Resource<Person> process(Resource<Person> resource) {

      resource.add(new Link("http://localhost:8080/people", "added-link"));
      return resource;
     }
   };
}

Obviously hard coding is bad so how do I write such component that can dynamically get the path for another resource in the application?

The obvious solution would seem to be to inject an instance of RepositoryRestConfiguration however all look-ups in this area on the injected configuration return null even though the repository is exposed and working for this resource.

Other data such as Projection definitions, classes with IDs etc are present in the injected RepositoryRestConfiguration as expected. So why do I get null for these look-ups?

@Component
public class CaseResourceProcessor implements ResourceProcessor<Resource<Case>>
{
  @Autowired
  private RepositoryRestConfiguration configuration;

  @Override
  public Resource<Case> process(Resource<Case> resource)
  {
    //null
    configuration.getResourceMappingForDomainType(Submission.class).getPath();

    //null
    configuration.getResourceMappingForRepository(SubmissionRepository.class).getPath();

    resource.add(new Link("...."));

    return resource;
  }
}

Much of the code in this area is deprecated however it is not clear exactly what should be used instead (although I would expect the deprecated code to rmain functional).

Essentially then, how do I programatically discover the URL for a specific Entity or Repository.

like image 579
Alan Hay Avatar asked Mar 11 '23 18:03

Alan Hay


1 Answers

Found that this can be done as follows:

@Component
public class CaseResourceProcessor implements ResourceProcessor<Resource<Case>>
{
  @Autowired
  private RepositoryRestMvcConfiguration configuration;

  @Override
  public Resource<Case> process(Resource<Case> resource)
  {
    LinkBuilder link = configuration.entityLinks().linkForSingleResource(Submission.class,
        resource.getContent().getLatestSubmission().getId());

    resource.add(link.withRel("latestSubmission"));

    return resource;
  }
}
like image 114
Alan Hay Avatar answered Mar 19 '23 13:03

Alan Hay