跳到主要内容

自定义仓储实现

DeepSeek V3 中英对照 Custom Repository Implementations

Spring Data 提供了多种选项来创建查询方法,只需少量编码。但当这些选项无法满足你的需求时,你也可以为仓库方法提供自定义实现。本节将介绍如何做到这一点。

自定义单个仓库

要为存储库增加自定义功能,首先需要定义一个片段接口以及该自定义功能的实现,如下所示:

interface CustomizedUserRepository {
void someCustomMethod(User user);
}
java
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

@Override
public void someCustomMethod(User user) {
// Your custom implementation
}
}
java
备注

与片段接口对应的类名中最重要的部分是 Impl 后缀。你可以通过设置 @Enable<StoreModule>Repositories(repositoryImplementationPostfix = …) 来自定义存储特定的后缀。

注意

历史上,Spring Data 自定义仓库实现的发现遵循了一种命名模式,该模式从仓库中派生出自定义实现类的名称,从而有效地允许单一自定义实现。

位于与仓库接口相同包中的类型,如果匹配仓库接口名称后跟实现后缀,则被视为自定义实现,并将被当作自定义实现处理。遵循该名称的类可能会导致不希望的行为。

我们认为单一自定义实现的命名方式已被弃用,并建议不要使用这种模式。相反,建议迁移到基于片段的编程模型。

实现本身并不依赖于 Spring Data,可以是一个普通的 Spring bean。因此,你可以使用标准的依赖注入行为来注入对其他 bean 的引用(例如 JdbcTemplate),参与到切面中,等等。

然后你可以让你的仓库接口扩展片段接口,如下所示:

interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {

// Declare query methods here
}
java

通过将你的仓库接口与片段接口扩展,可以将 CRUD 和自定义功能结合起来,并使其对客户端可用。

Spring Data 仓库是通过使用片段来实现的,这些片段构成了一个仓库组合。片段包括基础仓库、功能方面(例如 Querydsl)以及自定义接口及其实现。每次向仓库接口添加一个接口时,都会通过添加一个片段来增强组合。基础仓库和仓库方面的实现由每个 Spring Data 模块提供。

以下示例展示了自定义接口及其实现:

interface HumanRepository {
void someHumanMethod(User user);
}

class HumanRepositoryImpl implements HumanRepository {

@Override
public void someHumanMethod(User user) {
// Your custom implementation
}
}

interface ContactRepository {

void someContactMethod(User user);

User anotherContactMethod(User user);
}

class ContactRepositoryImpl implements ContactRepository {

@Override
public void someContactMethod(User user) {
// Your custom implementation
}

@Override
public User anotherContactMethod(User user) {
// Your custom implementation
}
}
java

以下示例展示了一个扩展 CrudRepository 的自定义仓库的接口:

interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {

// Declare query methods here
}
java

存储库可能由多个自定义实现组成,这些实现按其声明的顺序导入。自定义实现的优先级高于基础实现和存储库方面。这种排序方式允许您覆盖基础存储库和方面方法,并在两个片段提供相同方法签名时解决歧义。存储库片段不仅限于在单个存储库接口中使用。多个存储库可以使用一个片段接口,从而使您能够在不同的存储库之间重用自定义内容。

以下示例展示了一个存储库片段及其实现:

interface CustomizedSave<T> {
<S extends T> S save(S entity);
}

class CustomizedSaveImpl<T> implements CustomizedSave<T> {

@Override
public <S extends T> S save(S entity) {
// Your custom implementation
}
}
java

以下示例展示了一个使用上述代码片段的仓库:

interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}

interface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {
}
java

配置

仓库基础设施尝试通过扫描在其找到仓库的包下的类来自动检测自定义实现片段。这些类需要遵循命名约定,默认情况下附加一个后缀 Impl

以下示例展示了一个使用默认后缀的存储库,以及一个为后缀设置了自定义值的存储库:

示例 1. 配置示例

@EnableElasticsearchRepositories(repositoryImplementationPostfix = "MyPostfix")
class Configuration {}
java

在前面的示例中,第一个配置尝试查找一个名为 com.acme.repository.CustomizedUserRepositoryImpl 的类,作为自定义的仓库实现。第二个示例尝试查找 com.acme.repository.CustomizedUserRepositoryMyPostfix

歧义解决

如果在不同的包中找到具有匹配类名的多个实现,Spring Data 使用 bean 名称来标识要使用哪一个。

给定以下两个针对前面展示的 CustomizedUserRepository 的自定义实现,第一个实现被使用。它的 bean 名称为 customizedUserRepositoryImpl,这与片段接口(CustomizedUserRepository)的名称加上后缀 Impl 相匹配。

示例 2. 解决实现歧义

package com.acme.impl.one;

class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

// Your custom implementation
}
java
package com.acme.impl.two;

@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

// Your custom implementation
}
java

如果你在 UserRepository 接口上使用 @Component("specialCustom") 注解,那么 bean 名称加上 Impl 后就会与 com.acme.impl.two 中定义的仓库实现相匹配,并且会使用这个实现而不是第一个。

手动装配

如果你的自定义实现仅使用基于注解的配置和自动装配,那么前面展示的方法效果很好,因为它被视为任何其他 Spring Bean 一样处理。如果你的实现片段 Bean 需要特殊的装配,你可以声明该 Bean 并根据前一节中描述的约定为其命名。然后,基础设施会通过名称引用手动定义的 Bean 定义,而不是自己创建一个。以下示例展示了如何手动装配一个自定义实现:

示例 3. 自定义实现的手动连接

class MyClass {
MyClass(@Qualifier("userRepositoryImpl") UserRepository userRepository) {

}
}
java

使用 spring.factories 注册片段

正如在配置部分已经提到的,基础设施只会自动检测仓库基础包内的片段。因此,如果片段位于其他位置或希望通过外部存档贡献,且它们没有共享一个共同的命名空间,那么这些片段将不会被找到。在 spring.factories 中注册片段可以让你绕过这个限制,如下一节所述。

假设你想为你的组织提供一些自定义的搜索功能,这些功能可以在多个仓库中使用,并利用文本搜索索引。

首先你需要的是片段接口。注意泛型 <T> 参数,用于将片段与仓库领域类型对齐。

package com.acme.search;

public interface SearchExtension<T> {

List<T> search(String text, Limit limit);
}
java

假设实际的全文搜索功能可以通过一个 SearchService 实现,该服务在上下文中注册为一个 Bean,因此你可以在 SearchExtension 实现中使用它。运行搜索所需的所有内容就是集合(或索引)名称以及一个将搜索结果转换为实际领域对象的对象映射器,如下所示。

package com.acme.search;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Limit;
import org.springframework.data.repository.core.RepositoryMethodContext;

class DefaultSearchExtension<T> implements SearchExtension<T> {

private final SearchService service;

DefaultSearchExtension(SearchService service) {
this.service = service;
}

@Override
public List<T> search(String text, Limit limit) {
return search(RepositoryMethodContext.getContext(), text, limit);
}

List<T> search(RepositoryMethodContext metadata, String text, Limit limit) {

Class<T> domainType = metadata.getRepository().getDomainType();

String indexName = domainType.getSimpleName().toLowerCase();
List<String> jsonResult = service.search(indexName, text, 0, limit.max());

return jsonResult.stream().map().collect(toList());
}
}
java

在上面的例子中,RepositoryMethodContext.getContext() 用于检索实际方法调用的元数据。RepositoryMethodContext 暴露了附加到存储库的信息,例如域类型。在这种情况下,我们使用存储库域类型来识别要搜索的索引名称。

暴露调用元数据的代价较高,因此默认情况下是禁用的。要访问 RepositoryMethodContext.getContext(),你需要建议负责创建实际存储库的存储库工厂暴露方法元数据。

RepositoryMetadataAccess 标记接口添加到片段实现中,将触发基础设施并为使用该片段的仓库启用元数据暴露。

package com.acme.search;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Limit;
import org.springframework.data.repository.core.support.RepositoryMetadataAccess;
import org.springframework.data.repository.core.RepositoryMethodContext;

class DefaultSearchExtension<T> implements SearchExtension<T>, RepositoryMetadataAccess {

// ...
}
java

在准备好片段声明和实现之后,你可以在 META-INF/spring.factories 文件中注册扩展,并在需要时打包相关内容。

com.acme.search.SearchExtension=com.acme.search.DefaultSearchExtension
properties

现在你已经准备好使用你的扩展了;只需将接口添加到你的仓库中即可。

package io.my.movies;

import com.acme.search.SearchExtension;
import org.springframework.data.repository.CrudRepository;

interface MovieRepository extends CrudRepository<Movie, String>, SearchExtension<Movie> {

}
java

自定义基础仓库

上一节 中描述的方法需要在你想自定义基础仓库行为时对每个仓库接口进行定制,以便所有仓库都受到影响。为了改变所有仓库的行为,你可以创建一个扩展了特定持久化技术仓库基类的实现。然后,这个类将作为仓库代理的自定义基类,如下例所示:

class MyRepositoryImpl<T, ID>
extends SimpleJpaRepository<T, ID> {

private final EntityManager entityManager;

MyRepositoryImpl(JpaEntityInformation entityInformation,
EntityManager entityManager) {
super(entityInformation, entityManager);

// Keep the EntityManager around to used from the newly introduced methods.
this.entityManager = entityManager;
}

@Override
@Transactional
public <S extends T> S save(S entity) {
// implementation goes here
}
}
java
警告

该类需要具有超类的构造函数,存储特定的仓库工厂实现会使用该构造函数。如果仓库基类有多个构造函数,请重写接受 EntityInformation 加上存储特定基础设施对象(如 EntityManager 或模板类)的构造函数。

最后一步是让 Spring Data 基础设施知道自定义的仓库基类。在配置中,你可以通过使用 repositoryBaseClass 来实现这一点,如下例所示:

示例 4. 配置自定义仓库基类

@Configuration
@EnableElasticsearchRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration {}
java