自定义存储库实现

Spring Data 提供了多种选项,只需少量编码即可创建查询方法。但是,当这些选项不符合您的需求时,您也可以为存储库方法提供自己的自定义实现。本节将介绍如何实现此功能。

自定义单个存储库

要使用自定义功能丰富存储库,您必须首先定义一个片段接口和该自定义功能的实现,如下所示

自定义存储库功能的接口
interface CustomizedUserRepository {
  void someCustomMethod(User user);
}
自定义存储库功能的实现
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

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

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

从历史上看,Spring Data 自定义存储库实现的发现遵循一种命名模式,该模式从存储库派生自定义实现类名,实际上只允许一个自定义实现。

位于与存储库接口相同包中、匹配*存储库接口名称*后跟*实现后缀*的类型被视为自定义实现,并将被视为自定义实现。遵循该名称的类可能会导致意外行为。

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

实现本身不依赖于 Spring Data,并且可以是常规的 Spring bean。因此,您可以使用标准的依赖注入行为来注入对其他 bean(例如 JdbcTemplate)的引用,参与切面等等。

然后,您可以让您的存储库接口继承该片段接口,如下所示

对您的存储库接口的更改
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {

  // Declare query methods here
}

使用您的存储库接口扩展片段接口将 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
  }
}

以下示例展示了继承 CrudRepository 的自定义存储库接口

对您的存储库接口的更改
interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {

  // Declare query methods here
}

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

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

覆盖 save(…​) 的片段
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
  }
}

以下示例展示了使用前述存储库片段的存储库

定制的存储库接口
interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}

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

配置

存储库基础设施尝试通过扫描找到存储库的包下的类来自动检测自定义实现片段。这些类需要遵循附加后缀(默认为 Impl)的命名约定。

以下示例展示了使用默认后缀的存储库和为后缀设置自定义值的存储库

示例 1. 配置示例
  • Java

  • XML

@EnableJpaRepositories(repositoryImplementationPostfix = "MyPostfix")
class Configuration { … }
<repositories base-package="com.acme.repository" />

<repositories base-package="com.acme.repository" repository-impl-postfix="MyPostfix" />

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

歧义解析

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

考虑到前面所示的 CustomizedUserRepository 的以下两个自定义实现,将使用第一个实现。其 bean 名称是 customizedUserRepositoryImpl,这与片段接口 (`CustomizedUserRepository`) 加上后缀 Impl 的名称匹配。

示例 2. 歧义实现的解析
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  // Your custom implementation
}
@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  // Your custom implementation
}

如果您使用 @Component("specialCustom") 注解 UserRepository 接口,则 bean 名称加上 Impl 将与 com.acme.impl.two 中为存储库实现定义的名称匹配,并将使用它而不是第一个实现。

手动装配

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

示例 3. 自定义实现的手动装配
  • Java

  • XML

class MyClass {
  MyClass(@Qualifier("userRepositoryImpl") UserRepository userRepository) {
    …
  }
}
<repositories base-package="com.acme.repository" />

<beans:bean id="userRepositoryImpl" class="…">
  <!-- further configuration -->
</beans:bean>

使用 spring.factories 注册片段

正如在配置一节中已经提到的,基础设施只会在存储库基础包内自动检测片段。因此,如果片段位于其他位置或希望由外部归档文件贡献,则如果它们不共享共同命名空间,将无法找到。在 spring.factories 中注册片段允许您绕过此限制,如下一节所述。

想象一下,您希望为您的组织提供一些可跨多个存储库使用的自定义搜索功能,利用文本搜索索引。

首先,您只需要片段接口。请注意泛型参数 <T>,用于将片段与存储库域类型对齐。

片段接口
public interface SearchExtension<T> {

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

假设实际的全文本搜索通过一个在上下文中注册为 BeanSearchService 提供,以便您可以在我们的 SearchExtension 实现中使用它。您运行搜索所需的一切就是集合(或索引)名称以及一个将搜索结果转换为实际域对象的对象映射器,如下所述。

片段实现
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());
    }
}

在上面的示例中,RepositoryMethodContext.getContext() 用于检索实际方法调用的元数据。RepositoryMethodContext 公开附属于存储库的信息,例如域类型。在本例中,我们使用存储库域类型来标识要搜索的索引名称。

公开调用元数据开销很大,因此默认情况下是禁用的。要访问 RepositoryMethodContext.getContext(),您需要对负责创建实际存储库的存储库工厂进行通知,以公开方法元数据。

公开存储库元数据
  • 标记接口

  • Bean 后处理器

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

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 {

    // ...
}

exposeMetadata 标志可以通过 BeanPostProcessor 直接在存储库工厂 bean 上设置。

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
import org.springframework.lang.Nullable;

@Configuration
class MyConfiguration {

    @Bean
    static BeanPostProcessor exposeMethodMetadata() {

        return new BeanPostProcessor() {

            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) {

                if(bean instanceof RepositoryFactoryBeanSupport<?,?,?> factoryBean) {
                    factoryBean.setExposeMetadata(true);
                }
                return bean;
            }
        };
    }
}

请不要只是复制/粘贴上面的内容,而是考虑您的实际用例,这可能需要更精细的方法,因为上述方法只会简单地在每个存储库上启用该标志。

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

META-INF/spring.factories 中注册片段
com.acme.search.SearchExtension=com.acme.search.DefaultSearchExtension

现在您就可以使用您的扩展了;只需将接口添加到您的存储库中即可。

使用示例
import com.acme.search.SearchExtension;
import org.springframework.data.repository.CrudRepository;

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

}

自定义基础存储库

当您想要自定义基础存储库行为以影响所有存储库时,前一节中描述的方法需要自定义每个存储库接口。要更改所有存储库的行为,您可以创建一个扩展特定持久化技术存储库基类的实现。然后,此类别将作为存储库代理的自定义基类,如下例所示

自定义存储库基类
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
  }
}
该类需要有一个其父类的构造函数,该构造函数由特定于存储的存储库工厂实现使用。如果存储库基类有多个构造函数,请覆盖接受 EntityInformation 加上特定于存储的基础设施对象(例如 EntityManager 或模板类)的那个构造函数。

最后一步是让 Spring Data 基础设施知道定制的存储库基类。在配置中,您可以使用 repositoryBaseClass 来做到这一点,如下例所示

示例 4. 配置自定义存储库基类
  • Java

  • XML

@Configuration
@EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
     base-class="….MyRepositoryImpl" />