自定义仓库实现
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。
因此,你可以使用标准的依赖注入行为来注入其他豆子的引用(例如Jdbc模板参与各个方面,等等。
然后你可以让你的仓库接口扩展片段界面,具体如下:
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
}
}
以下示例展示了扩展的自定义仓库接口原油仓库:
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.
以下示例展示了使用默认后缀的仓库和为后缀设置自定义值的仓库:
-
Java
-
XML
@EnableElasticsearchRepositories(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 会用豆名来确定使用哪一个。
给定以下两种自定义实现自定义用户仓库前面展示的,采用了第一种实现。
它的豆名是customizedUserRepositoryImpl,与片段接口的匹配(自定义用户仓库) 加上后缀impl.
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
// Your custom implementation
}
@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
// Your custom implementation
}
如果你在用户仓库与@Component(“特殊定制”),豆名加impl然后与仓库实现定义的com.acme.impl.two,并且用它代替第一个。
手动布线
如果你的自定义实现只使用基于注释的配置和自动配线,前面展示的方法效果很好,因为它被视为普通的 Spring 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。工厂允许你绕过以下部分解释的限制。
想象你想为你的组织提供一些可跨多个仓库使用的自定义搜索功能,利用文本搜索索引。
首先你只需要一个碎片接口。
注意 generic<了>参数用于将片段与仓库域类型对齐。
public interface SearchExtension<T> {
List<T> search(String text, Limit limit);
}
假设实际的全文搜索可以通过SearchService注册为豆在上下文中,你可以在我们的搜索扩展实现。
运行搜索所需的只需集合(或索引)名称和一个对象映射器,将搜索结果转换为如下所述的实际域对象。
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
添加RepositoryMetadataAccess与片段实现的标记接口将触发基础设施,并使使用片段的仓库能够暴露元数据。
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标志可以通过 A 直接在仓库的工厂豆上设置豆子后处理器.
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.factoriescom.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
}
}
类需要有一个超类的构造子,而该构造器是存储仓库工厂实现所使用的。
如果仓库基类有多个构造函数,则覆盖那个承载实体信息此外,存储特定基础设施对象(例如实体管理器或者模板类)。 |
最后一步是让 Spring Data 基础设施知道自定义的仓库基类。
在配置中,你可以通过使用repositoryBaseClass如下例所示:
-
Java
-
XML
@Configuration
@EnableElasticsearchRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
base-class="….MyRepositoryImpl" />