创建仓库实例

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

Java 配置

在 Java 配置类上使用特定于存储的 `@EnableCouchbaseRepositories` 注解来定义仓库激活配置。有关 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 类型名称作为前缀。base package 属性允许使用通配符,这样你就可以定义扫描包的模式。

使用过滤器

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

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

使用过滤器
  • Java

  • XML

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