自定义仓库实现
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
@EnableJdbcRepositories(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. 歧义实现的解析
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 中为该仓库实现定义的名称相匹配,从而使用它而不是第一个。
手动装配
如果您的自定义实现仅使用基于注解的配置和自动装配,那么前述方法就很适用,因为它被当作任何其他 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 注册片段
如配置一节所述,基础设施只自动检测仓库基础包内的片段。因此,位于其他位置、或希望由外部归档提供的片段,如果不共享公共命名空间,就不会被发现。在 spring.factories 中注册片段可以让您绕过这一限制,如下一节所述。
设想您希望利用文本搜索索引,为组织提供一种可跨多个仓库使用的自定义搜索功能。
首先,您只需要片段接口。注意泛型 <T> 参数,用于使片段与仓库领域类型保持一致。
public interface SearchExtension<T> {
List<T> search(String text, Limit limit);
}
假设实际的全文搜索通过一个 SearchService 提供,该服务在上下文中注册为一个 Bean,这样您就可以在我们的 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 暴露附加到仓库的信息,如领域类型。在本例中,我们使用仓库领域类型来标识要搜索的索引名称。
暴露调用元数据代价高昂,因此默认禁用。要访问 RepositoryMethodContext.getContext(),您需要告知负责创建实际仓库的仓库工厂暴露方法元数据。
- Marker Interface
- Bean Post Processor
Adding the RepositoryMetadataAccess marker interface to the fragments implementation will trigger the infrastructure and enable metadata exposure for those repositories using the fragment.
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 {
// ...
}
The exposeMetadata flag can be set directly on the repository factory bean via a BeanPostProcessor.
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
@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;
}
};
}
}
Please do not just copy/paste the above but consider your actual use case which may require a more fine-grained approach as the above will simply enable the flag on every repository.
在片段声明和实现都就绪后,您就可以在 META-INF/spring.factories 文件中注册该扩展,并在需要时打包。
com.acme.search.SearchExtension=com.acme.search.DefaultSearchExtension
现在您就可以使用自己的扩展了;只需将该接口添加到您的仓库即可。
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
@EnableJdbcRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
base-class="….MyRepositoryImpl" />
定制仓库工厂
通过 RepositoryFactoryCustomizer 定制仓库工厂,可以直接访问参与仓库实例创建的各个组件。当您想调整代理创建的某些方面,而又不想引入完全自定义的仓库工厂 bean 时,该机制很有用。以下示例演示了如何注册额外的监听器和代理通知器:
factoryBean.addRepositoryFactoryCustomizer(repositoryFactory -> {
repositoryFactory.addInvocationListener(…);
repositoryFactory.addQueryCreationListener(…);
repositoryFactory.addRepositoryProxyPostProcessor((factory, repositoryInformation) -> factory.addAdvice(…));
});
RepositoryFactoryCustomizer 与特定的仓库工厂 bean 相关联,理想情况下通过 BeanPostProcessor 实现,以便只影响特定的仓库。请注意,customizer bean 不会自动应用,以防止不必要的装配——这在多仓库安排或使用多个 Spring Data 模块时尤其重要。
定制仓库工厂 Bean
定制仓库创建最强大的方式是提供一个自定义仓库工厂 bean,通常是 RepositoryFactorySupport、TransactionalRepositoryFactoryBeanSupport 或特定存储仓库工厂 bean 的子类。
定制仓库工厂 bean 让您可以完全掌控底层仓库工厂,从而彻底改变仓库的创建方式。
请注意,这种方式所需工作量最大,通常只在您想改变仓库创建的核心方面时才需要。此外,您还需要考虑用于识别查询方法、基础实现方法和自定义实现的仓库元数据派生。以下小结概述了关键方面:
-
repositoryBaseClass:仓库基类定义哪些方法由基类实现,哪些方法需要通过切面或自定义实现进行额外处理。 -
repositoryFragmentsContributor:一个 RepositoryFragmentsContributor,允许在收集完所有标准片段后为仓库组合贡献内容。存储模块使用该机制添加 Querydsl 或按示例查询等功能。它同时也是第三方扩展的 SPI。 -
exposeMetadata:控制是否可通过RepositoryMethodContext.getContext()获取调用元数据。