考虑Custom implementations for Spring Data repositories我在存储库上使用 @RepositoryRestResource
来带来所有 HATEOAS 生成的好处:
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<PersonNode,Long>,
PersonRepositoryCustom {
List<PersonNode> findBySurname(@Param("0") String name);
}
现在,按照提到的文档,我使用附加的简单方法创建了 PersonRepositoryCustom
,用于介绍性目的:
public interface PersonRepositoryCustom {
public String printPerson(PersonNode personNode);
}
实现是:
public class PersonRepositoryImpl implements PersonRepositoryCustom{
@Override
public String printPerson(PersonNode personNode) {
return "It Works!";
}
}
我希望保留默认的 SDR 自动生成的端点,只添加新的自定义方法/新的实现。 我应该如何将这个自定义方法与 spring-data Rest/HATEOAS 一起使用? 使用简单的@RepositoryRestResource, Controller 端点是自动生成的。如果我想提供一些自定义方法怎么办?我想我必须手动创建 Controller ,但在这个示例案例中它应该是什么样子?
最佳答案
首先,像 public String printPerson(PersonNode personNode)
这样的存储库方法是一种 RPC 风格的 API,并且是一种已知的反模式,因此您应该在 REST 中设计您的 API -兼容方式(参见例如 How to design REST API for non-CRUD "commands" like activate and deactivate of a resource? )
您的问题的解决方案如下所示:
使用为自定义方法定义的
<@RequestMapping
创建一个自定义@RestController
(如您所想),该方法调用相关实现。为您的实体创建一个新的
ResourceProcessor
并覆盖其process
方法,添加指向资源的新链接以指向您的自定义方法,例如/people/{id}/printPerson
或任何您的映射定义。
这是我的项目中的一个示例(博客
实体需要列出其类别
):
@Component
public static class BlogResourceProcessor implements ResourceProcessor<Resource<Blog>> {
@Override
public Resource<Blog> process(Resource<Blog> blogResource) {
UriComponents uriComponents = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/blog/{id}/categories").buildAndExpand(Long.toString(blogResource.getContent().getId()));
blogResource.add(new Link(uriComponents.toUriString(), "categories"));
return blogResource;
}
}
关于spring-mvc - Spring Data Rest/HATEOAS 与自定义方法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34379695/