简体   繁体   中英

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.

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM