Integration

本部分详细介绍了各种与 Spring Data REST 组件集成的途径,无论是从使用 Spring Data REST 的 Spring 应用程序还是通过其他途径。

This section details various ways to integrate with Spring Data REST components, whether from a Spring application that is using Spring Data REST or from other means.

有时,您需要在自定义构建的 Spring MVC 控制器中向导出的资源添加链接。提供三个基本的链接级别:

Sometimes you need to add links to exported resources in your own custom-built Spring MVC controllers. There are three basic levels of linking available:

  • Manually assembling links.

  • Using Spring HATEOAS’s LinkBuilder with linkTo(), slash(), and so on.

  • Using Spring Data REST’s implementation of RepositoryEntityLinks.

第一个建议很糟糕,应不惜一切代价避免。它会使您的代码变得脆弱且风险很高。创建与其他手写 Spring MVC 控制器之间的链接时,第二个建议很方便。最后一个,我们将在本部分的其余部分介绍,非常适合查找由 Spring Data REST 导出的资源链接。

The first suggestion is terrible and should be avoided at all costs. It makes your code brittle and high-risk. The second is handy when creating links to other hand-written Spring MVC controllers. The last one, which we explore in the rest of this section, is good for looking up resource links that are exported by Spring Data REST.

考虑使用 Spring 自动装配的以下类:

Consider the following class ,which uses Spring’s autowiring:

public class MyWebApp {

	private RepositoryEntityLinks entityLinks;

	@Autowired
	public MyWebApp(RepositoryEntityLinks entityLinks) {
		this.entityLinks = entityLinks;
	}
}

使用前一个示例中的类,您可以使用以下操作:

With the class in the preceding example, you can use the following operations:

Table 1. Ways to link to exported resources
Method Description

entityLinks.linkToCollectionResource(Person.class)

Provide a link to the collection resource of the specified type (Person, in this case).

entityLinks.linkToItemResource(Person.class, 1)

Provide a link to a single resource.

entityLinks.linkToPagedResource(Person.class, new PageRequest(…​))

Provide a link to a paged resource.

entityLinks.linksToSearchResources(Person.class)

Provides a list of links for all the finder methods exposed by the corresponding repository.

entityLinks.linkToSearchResource(Person.class, "findByLastName")

Provide a finder link by rel (that is, the name of the finder).

所有基于搜索的链接都支持分页和排序的附加参数。有关详细信息,请参阅 link:https://docs.spring.io/spring-data/rest/docs/current/api/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.html[RepositoryEntityLinks。还有 linkFor(Class<?> type),但它会返回一个 Spring HATEOAS LinkBuilder,它会将您返回到较低级别的 API。请首先尝试使用其他的。

All of the search-based links support extra parameters for paging and sorting. See RepositoryEntityLinks for the details. There is also linkFor(Class<?> type), but that returns a Spring HATEOAS LinkBuilder, which returns you to the lower level API. Try to use the other ones first.