创建仓库实例
本节介绍如何为定义的仓库接口创建实例和 Bean 定义。
Java 配置
在 Java 配置类上使用特定于存储的 `@EnableElasticsearchRepositories` 注解来定义仓库激活配置。有关 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 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 名称会加上其封闭类型名称作为前缀。基础包属性允许使用通配符,以便您可以定义扫描包的模式。
使用过滤器
默认情况下,基础设施会查找配置的基础包下扩展特定于持久化技术的 `Repository` 子接口的每个接口,并为其创建一个 Bean 实例。但是,您可能希望更精细地控制为哪些接口创建 Bean 实例。为此,请在仓库声明中使用过滤器元素。其语义与 Spring 的组件过滤器中的元素完全等效。有关详细信息,请参阅 Spring 参考文档中关于这些元素的说明。
例如,要将某些接口排除在外,不创建仓库 Bean 实例,您可以使用以下配置
-
Java
-
XML
@Configuration
@EnableElasticsearchRepositories(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);