自定义 Repository 实现
Spring Data 提供了多种选项,只需少量编码即可创建查询方法。但当这些选项不满足您的需求时,您也可以为 repository 方法提供自己的自定义实现。本节将介绍如何实现。
自定义单个 Repository
要使用自定义功能丰富一个 repository,您必须首先为该自定义功能定义一个 fragment 接口及其实现,如下所示
interface CustomizedUserRepository {
void someCustomMethod(User user);
}
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
@Override
public void someCustomMethod(User user) {
// Your custom implementation
}
}
与 fragment 接口对应的类名中最重要的部分是 |
从历史上看,Spring Data 自定义 repository 实现的发现遵循一种命名模式,该模式从 repository 派生自定义实现类名,从而有效地只允许单个自定义实现。 位于与 repository 接口相同包中、且名称与repository 接口名称后跟实现后缀匹配的类型,被视为自定义实现并将被当作自定义实现处理。遵循该名称的类可能导致意外行为。 我们认为单自定义实现命名模式已被弃用,建议不再使用此模式。请迁移到基于 fragment 的编程模型。 |
实现本身不依赖于 Spring Data,它可以是一个普通的 Spring bean。因此,您可以使用标准的依赖注入行为来注入对其他 bean(例如 JdbcTemplate
)的引用,参与切面等。
然后您可以让您的 repository 接口扩展该 fragment 接口,如下所示
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {
// Declare query methods here
}
让您的 repository 接口扩展 fragment 接口将 CRUD 和自定义功能结合起来,并使其可供客户端使用。
Spring Data repositories 是通过构成 repository 组合的 fragment 来实现的。Fragment 包括基本 repository、功能切面(例如 Querydsl)以及自定义接口及其实现。每次向您的 repository 接口添加一个接口时,您都是通过添加一个 fragment 来增强该组合。基本 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 的接口
interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {
// Declare query methods here
}
Repositories 可以由多个自定义实现组成,这些实现按照其声明的顺序导入。自定义实现的优先级高于基本实现和 repository 切面。这种顺序允许您覆盖基本 repository 和切面方法,并在两个 fragment 贡献相同方法签名时解决歧义。Repository fragment 不仅限于在一个 repository 接口中使用。多个 repositories 可以使用同一个 fragment 接口,从而允许您在不同的 repositories 中重用定制。
以下示例展示了一个 repository fragment 及其实现
save(…)
的 Fragmentinterface 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 fragment 的 repository
interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}
interface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {
}
配置
repository 基础设施会尝试通过扫描在其找到 repository 的包下的类来自动检测自定义实现 fragment。这些类需要遵循附加后缀的命名约定,默认后缀为 Impl
。
以下示例展示了一个使用默认后缀的 repository 和一个为后缀设置自定义值的 repository
-
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
,这与 fragment 接口 (CustomizedUserRepository
) 加上后缀 Impl
的名称匹配。
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 处理。如果您的实现 fragment bean 需要特殊连接,您可以按照前一节中描述的约定声明并命名该 bean。然后基础设施将按名称引用手动定义的 bean 定义,而不是自己创建一个。以下示例展示了如何手动连接自定义实现
-
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 注册 Fragment
正如配置部分已经提到的,基础设施只会在 repository 基本包内自动检测 fragment。因此,如果 fragment 位于其他位置或需要由外部存档贡献,并且它们不共享一个共同的命名空间,那么它们将不会被找到。在 spring.factories
中注册 fragment 可以让您规避此限制,如下一节所述。
假设您希望为您的组织提供一些可跨多个 repository 使用的自定义搜索功能,并利用文本搜索索引。
首先,您需要的是 fragment 接口。请注意泛型参数 <T>
,以便将 fragment 与 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 factory 来暴露方法元数据。
-
标记接口
-
Bean 后置处理器
将 RepositoryMetadataAccess
标记接口添加到 fragment 实现将触发基础设施并为使用该 fragment 的 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 factory 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 上启用该标志。
声明和实现 fragment 都到位后,您可以在 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 代理的自定义基类,如下例所示
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
}
}
该类需要拥有 store 特定 repository factory 实现使用的父类构造函数。如果 repository 基类有多个构造函数,请重写接受 EntityInformation 以及 store 特定基础设施对象(例如 EntityManager 或模板类)的构造函数。 |
最后一步是让 Spring Data 基础设施知晓自定义的 repository 基类。在配置中,您可以通过使用 repositoryBaseClass
来实现,如下例所示
-
Java
-
XML
@Configuration
@EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
base-class="….MyRepositoryImpl" />