自定义 Repository 实现

Spring Data 提供了多种选项,只需少量编码即可创建查询方法。但当这些选项不满足您的需求时,您也可以为 Repository 方法提供自己的自定义实现。本节介绍如何实现这一点。

自定义单个 Repository

要使用自定义功能丰富 Repository,您必须首先为自定义功能定义一个分片接口和实现,如下所示:

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

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

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

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

与 Repository 接口位于同一包中、名称与Repository 接口名称加上实现后缀匹配的类型,会被视为自定义实现并按自定义实现处理。遵循该名称的类可能导致意外行为。

我们认为单一自定义实现命名已过时,建议不再使用此模式。请迁移到基于分片的编程模型。

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

然后,您可以让您的 Repository 接口继承该分片接口,如下所示:

对 Repository 接口的更改
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {

  // Declare query methods here
}

通过让 Repository 接口继承分片接口,将 CRUD 和自定义功能结合起来,并使其对客户端可用。

Spring Data Repository 通过使用形成 Repository 组合的分片来实现。分片包括基础 Repository、功能切面(例如 Querydsl)以及自定义接口及其实现。每次向 Repository 接口添加一个接口时,您都通过添加一个分片来增强组合。基础 Repository 和 Repository 切面实现由每个 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 的自定义 Repository 接口

对 Repository 接口的更改
interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {

  // Declare query methods here
}

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

以下示例展示了一个 Repository 分片及其实现

覆盖 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
  }
}

以下示例展示了使用上述 Repository 分片的 Repository

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

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

配置

Repository 基础设施会扫描找到 Repository 的包下的类,尝试自动检测自定义实现分片。这些类需要遵循命名约定,即附加一个后缀,默认为 Impl

以下示例展示了一个使用默认后缀的 Repository 和一个为后缀设置自定义值的 Repository

示例 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 的类作为自定义 Repository 实现。第二个示例尝试查找 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 中为 Repository 实现定义的名称匹配,并使用它而不是第一个实现。

手动装配

如果您的自定义实现仅使用基于注解的配置和自动装配,上述方法效果很好,因为它被视为任何其他 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 注册分片

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

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

首先,您需要的是分片接口。请注意通用参数 <T>,它用于使分片与 Repository 域类型对齐。

分片接口
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 暴露了附加到 Repository 的信息,例如域类型。在这种情况下,我们使用 Repository 域类型来标识要搜索的索引名称。

暴露调用元数据是昂贵的,因此默认情况下是禁用的。要访问 RepositoryMethodContext.getContext(),您需要建议负责创建实际 Repository 的 Repository 工厂暴露方法元数据。

暴露 Repository 元数据
  • 标记接口

  • Bean Post Processor

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

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 {

    // ...
}

可以通过 BeanPostProcessor 直接在 Repository 工厂 Bean 上设置 exposeMetadata 标志。

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;
            }
        };
    }
}

请不要直接复制/粘贴上述内容,而是考虑您的实际用例,这可能需要更细粒度的方法,因为上述方法将简单地在每个 Repository 上启用该标志。

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

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

现在您可以开始使用您的扩展了;只需将接口添加到您的 Repository 中即可。

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

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

}

定制基础 Repository

上一节中描述的方法需要定制每个 Repository 接口才能定制基础 Repository 的行为,以便所有 Repository 都受到影响。若要改为更改所有 Repository 的行为,您可以创建一个扩展特定持久化技术的基础 Repository 类的实现。然后,此类别将作为 Repository 代理的自定义基础类,如以下示例所示:

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

最后一步是让 Spring Data 基础设施知道定制的基础 Repository 类。在配置中,您可以通过使用 repositoryBaseClass 来实现,如下例所示:

示例 4. 配置自定义基础 Repository 类
  • Java

  • XML

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