创建仓库实例
本节介绍如何为定义的仓库接口创建实例和 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 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
结尾的接口实例化。