创建仓库实例

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

Java 配置

在 Java 配置类上使用特定于存储的 @EnableRedisRepositories 注解来定义仓库激活配置。有关 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 名称以其 enclosing 类型名称作为前缀。基础包属性允许使用通配符,以便您可以定义扫描包的模式。

使用过滤器

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

例如,要从实例化为仓库 Bean 中排除某些接口,您可以使用以下配置

使用过滤器
  • Java

  • XML

@Configuration
@EnableRedisRepositories(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);