|
此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Data Couchbase 5.3.4! |
|
此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Data Couchbase 5.3.4! |
本节介绍如何为定义的存储库接口创建实例和 Bean 定义。
Java 配置
在 Java 配置类上使用特定于存储的注释来定义存储库激活的配置。
有关 Spring 容器的基于 Java 的配置的介绍,请参阅 Spring 参考文档中的 JavaConfig。@EnableCouchbaseRepositories
启用 Spring Data 存储库的示例配置类似于以下内容:
@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {
@Bean
EntityManagerFactory entityManagerFactory() {
// …
}
}
前面的示例使用特定于 JPA 的注释,您将根据实际使用的 store 模块更改该注释。这同样适用于 bean 的定义。请参阅涵盖特定于 store 的配置的部分。EntityManagerFactory |
前面的示例使用特定于 JPA 的注释,您将根据实际使用的 store 模块更改该注释。这同样适用于 bean 的定义。请参阅涵盖特定于 store 的配置的部分。EntityManagerFactory |
XML 配置
每个 Spring Data 模块都包含一个元素,该元素允许您定义 Spring 为您扫描的基本包,如以下示例所示:repositories
<?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 扫描及其所有子包以查找扩展接口或其子接口之一。
对于找到的每个接口,基础设施会注册特定于持久性技术的 Persistence 技术,以创建处理查询方法调用的相应代理。
每个 bean 都注册在从接口名称派生的 bean 名称下,因此接口 将在 下注册。
嵌套存储库接口的 Bean 名称以其封闭类型名称为前缀。
base package 属性允许使用通配符,以便您可以定义扫描的软件包的模式。com.acme.repositoriesRepositoryFactoryBeanUserRepositoryuserRepository
使用过滤器
默认情况下,基础架构会选取扩展位于已配置基础包下的特定于持久性技术的子接口的每个接口,并为其创建一个 bean 实例。
但是,您可能希望对哪些接口创建了 bean 实例进行更精细的控制。
为此,请在 repository 声明中使用 filter 元素。
语义与 Spring 的组件过滤器中的元素完全相同。
有关详细信息,请参阅这些元素的 Spring 参考文档。Repository
例如,要从实例化中排除某些接口作为存储库 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>
前面的示例包括所有以 结尾的接口,并不包括以 结尾的接口。SomeRepositorySomeOtherRepository
独立使用
您还可以在 Spring 容器之外使用存储库基础结构,例如,在 CDI 环境中。你的 Classpath 中仍然需要一些 Spring 库,但是,通常,你也可以通过编程方式设置存储库。提供存储库支持的 Spring Data 模块附带了您可以使用的特定于持久性技术的模块,如下所示:RepositoryFactory
RepositoryFactorySupport factory = … // Instantiate factory here
UserRepository repository = factory.getRepository(UserRepository.class);