自定义仓库实现
Spring Data 提供了多种选项来创建只需少量编码的查询方法。但当这些选项不符合你的需求时,你也可以为仓库方法提供自己的自定义实现。本节描述了如何做到这一点。
自定义单个仓库
为了用自定义功能丰富仓库,你必须首先定义一个片段接口和自定义功能的实现,如下所示
interface CustomizedUserRepository {
void someCustomMethod(User user);
}
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
@Override
public void someCustomMethod(User user) {
// Your custom implementation
}
}
与片段接口对应的类名中最重要的一部分是 |
历史上,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
的命名约定。
以下示例显示了一个使用默认后缀的仓库以及一个为后缀设置自定义值的仓库
-
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
相匹配。
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
接口,则 Bean 名称加上 Impl
将匹配在 com.acme.impl.two
中为仓库实现定义的名称,并且会使用它而不是第一个实现。
手动装配
如果你的自定义实现仅使用基于注解的配置和自动装配,则前面显示的方法效果很好,因为它被视为任何其他 Spring Bean。如果你的实现片段 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 注册片段
如 配置 部分所述,基础设施仅自动检测仓库基本包内的片段。因此,位于其他位置或希望由外部归档文件贡献的片段,如果它们不共享共同的命名空间,则不会被找到。在 spring.factories
中注册片段允许你规避此限制,如下一节所述。
假设你想为你的组织提供一些可跨多个仓库使用的自定义搜索功能,该功能利用了文本搜索索引。
首先,你需要的是片段接口。注意泛型参数 <T>
,以便将片段与仓库领域类型对齐。
package com.acme.search;
public interface SearchExtension<T> {
List<T> search(String text, Limit limit);
}
假设实际的全文搜索可通过一个在上下文中注册为 Bean
的 SearchService
获得,这样你就可以在我们的 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 {
// ...
}
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
现在你可以使用你的扩展了;只需将该接口添加到你的仓库中即可。
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
来做到这一点,如下例所示
-
Java
-
XML
@Configuration
@EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
base-class="….MyRepositoryImpl" />
在自定义实现中使用 JpaContext
当使用多个 EntityManager
实例和自定义仓库实现时,你需要将正确的 EntityManager
装配到仓库实现类中。你可以通过在 @PersistenceContext
注解中显式命名 EntityManager
,或者如果 EntityManager
被 @Autowired
注解,则使用 @Qualifier
来做到这一点。
从 Spring Data JPA 1.9 开始,Spring Data JPA 包含一个名为 JpaContext
的类,该类允许你通过托管领域类获取 EntityManager
,前提是它仅由应用程序中的一个 EntityManager
实例管理。以下示例展示了如何在自定义仓库中使用 JpaContext
JpaContext
class UserRepositoryImpl implements UserRepositoryCustom {
private final EntityManager em;
@Autowired
public UserRepositoryImpl(JpaContext context) {
this.em = context.getEntityManagerByManagedType(User.class);
}
…
}
这种方法的优点在于,如果领域类型被分配到不同的持久化单元,则无需修改仓库即可更改对持久化单元的引用。