建立倉庫例項
本節介紹如何為定義的倉庫介面建立例項和 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 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
結尾的介面不被例項化。