创建仓库实例

本节介绍如何为定义的仓库接口创建实例和 Bean 定义。

Java 配置

在 Java 配置类上使用特定于存储的 @EnableJpaRepositories 注解来定义仓库激活配置。有关 Spring 容器的基于 Java 的配置的介绍,请参阅 Spring 参考文档中的 JavaConfig

一个启用 Spring Data 仓库的示例配置如下所示

基于注解的仓库配置示例
@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {

  @Bean
  EntityManagerFactory entityManagerFactory() {
    // …
  }
}
前面的示例使用了 JPA 特定的注解,您需要根据实际使用的存储模块进行更改。这也适用于 EntityManagerFactory Bean 的定义。请参阅介绍特定存储配置的章节。

XML 配置

每个 Spring Data 模块都包含一个 repositories 元素,允许您定义一个 Spring 扫描的基础包,如下例所示

通过 XML 启用 Spring Data 仓库
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/data/jpa"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa
    https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <jpa:repositories base-package="com.acme.repositories" />

</beans:beans>

在前面的示例中,Spring 被指示扫描 com.acme.repositories 及其所有子包中扩展 Repository 或其子接口的接口。对于找到的每个接口,基础设施会注册特定于持久化技术的 FactoryBean,以创建处理查询方法调用的适当代理。每个 Bean 都以从接口名称派生的 Bean 名称进行注册,因此 UserRepository 接口将注册为 userRepository。嵌套仓库接口的 Bean 名称以其包含类型名称作为前缀。base-package 属性允许使用通配符,因此您可以定义要扫描的包的模式。

使用过滤器

默认情况下,基础设施会选取配置的基础包下所有扩展特定持久化技术的 Repository 子接口的接口,并为其创建 Bean 实例。但是,您可能希望对哪些接口创建 Bean 实例进行更精细的控制。为此,可以在仓库声明中使用 filter 元素。其语义与 Spring 组件过滤器中的元素完全等价。有关详细信息,请参阅 Spring 参考文档中关于这些元素的介绍。

例如,要将某些接口排除在仓库 Bean 实例化之外,可以使用以下配置

使用过滤器
  • Java

  • XML

@Configuration
@EnableJpaRepositories(basePackages = "com.acme.repositories",
    includeFilters = { @Filter(type = FilterType.REGEX, pattern = ".*SomeRepository") },
    excludeFilters = { @Filter(type = FilterType.REGEX, pattern = ".*SomeOtherRepository") })
class ApplicationConfiguration {

  @Bean
  EntityManagerFactory entityManagerFactory() {
    // …
  }
}
<repositories base-package="com.acme.repositories">
  <context:include-filter type="regex" expression=".*SomeRepository" />
  <context:exclude-filter type="regex" expression=".*SomeOtherRepository" />
</repositories>

前面的示例包含了所有以 SomeRepository 结尾的接口,并排除了以 SomeOtherRepository 结尾的接口不被实例化。

独立使用

您也可以在 Spring 容器之外使用仓库基础设施,例如在 CDI 环境中。您仍然需要在类路径中包含一些 Spring 库,但通常也可以通过编程方式设置仓库。提供仓库支持的 Spring Data 模块附带了特定于持久化技术的 RepositoryFactory,您可以如下使用它

仓库工厂的独立使用
RepositoryFactorySupport factory = … // Instantiate factory here
UserRepository repository = factory.getRepository(UserRepository.class);