自定义仓库实现
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
}
仓库可以由多个自定义实现组成,这些实现按照声明顺序导入。自定义实现的优先级高于基础实现和仓库方面。这种顺序允许你重写基础仓库和方面方法,并在两个片段贡献相同的方法签名时解决歧义。仓库片段不仅限于在单一仓库接口中使用。多个仓库可以使用同一个片段接口,从而让你在不同仓库之间重用自定义内容。
以下示例展示了一个存储库片段及其实现:
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
@EnableCassandraRepositories(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. 消除模糊实现的方案
package com.acme.impl.one;
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
// Your custom implementation
}
package com.acme.impl.two;
@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
// Your custom implementation
}
如果你用 @Component("specialCustom")
注解 UserRepository
接口,那么加上 Impl
的bean名称将匹配在 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 注册片段
作为在 Configuration 部分中已经提到的,基础设施仅在存储库的基础包内自动检测片段。因此,位于其他位置的片段或希望由外部档案贡献的片段,如果不共享公共命名空间,将无法被找到。在 spring.factories
中注册片段可以让你绕过这一限制,如下节所述。
想象一下,您希望为您的组织提供一种可以跨多个仓库使用的自定义搜索功能,利用文本搜索索引。
首先,您需要的是片段接口。请注意泛型 <T>
参数,用于将片段与仓库域类型对齐。
package com.acme.search;
public interface SearchExtension<T> {
List<T> search(String text, Limit limit);
}
假设实际的全文搜索通过一个 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());
}
}
在上面的示例中,RepositoryMethodContext.getContext()
被用来检索实际方法调用的元数据。RepositoryMethodContext
提供了附加到仓库的信息,例如域类型。在这种情况下,我们使用仓库域类型来识别要搜索的索引名称。
暴露调用元数据是有成本的,因此默认情况下是禁用的。要访问 RepositoryMethodContext.getContext()
,你需要建议负责创建实际仓库的仓库工厂来暴露方法元数据。
- 标记接口
- Bean 后置处理器
将 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 {
// ...
}
可以通过 BeanPostProcessor
在仓库工厂 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;
}
};
}
}
请不要仅仅复制/粘贴上面的代码,而是考虑您的实际用例,这可能需要更细粒度的方法,因为上述代码将简单地在每个仓库上启用标志。
有了了片段声明和实现,你可以在 META-INF/spring.factories
文件中注册扩展,并在需要时打包相关内容。
com.acme.search.SearchExtension=com.acme.search.DefaultSearchExtension
现在你已经准备好使用你的扩展;只需将接口添加到你的仓库中。
package io.my.movies;
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
@EnableCassandraRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
base-class="….MyRepositoryImpl" />