定制 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 repositories 是通过构成 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
}

Repositories 可以由多个定制实现组成,这些实现按照声明的顺序导入。定制实现的优先级高于基础实现和 repository 方面。这种排序使您可以覆盖基础 repository 和方面方法,并解决两个片段贡献相同方法签名时的歧义。Repository 片段不仅限于在单个 repository 接口中使用。多个 repositories 可以使用一个片段接口,从而允许您在不同 repositories 之间重用定制。

以下示例显示了一个 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 中注册片段允许您规避此限制,如下一节所述。

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

首先,您需要的是片段接口。请注意泛型参数 <T>,以便将片段与 repository 领域类型对齐。

片段接口
public interface SearchExtension<T> {

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

假设实际的全文搜索通过一个在上下文中注册为 Bean 的 SearchService 可用,因此您可以在 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 后置处理器

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

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 行为以便所有 repositories 都受影响的话。为了改为改变所有 repositories 的行为,您可以创建一个实现类,该类扩展特定持久化技术的基础 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" />