Spring Data Rest 资源上的自定义链接
Spring Data Rest 存储库指出可以将自定义链接添加到实体,如下所示:
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
示例:
@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?
显而易见的解决方案似乎是注入 RepositoryRestConfiguration 的一个实例,但是,即使存储库已公开并为该资源工作,该区域中注入的配置上的所有查找都返回 null.
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.
其他数据,如投影定义、带有 ID 的类等都按预期存在于注入的 RepositoryRestConfiguration 中.那么为什么我在这些查找中得到 null 呢?
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).
基本上,我如何以编程方式发现特定实体或存储库的 URL.
发现可以这样做:
@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;
}
}