建立倉庫例項

本節介紹如何為定義的倉庫介面建立例項和 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 啟用 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 名稱將以其外部型別名稱作為字首。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 結尾的介面例項化。

獨立使用

你也可以在 Spring 容器之外使用倉庫基礎設施,例如在 CDI 環境中。你仍然需要在類路徑中包含一些 Spring 庫,但通常你可以透過程式設計方式設定倉庫。提供倉庫支援的 Spring Data 模組附帶了特定於持久化技術的 RepositoryFactory,你可以按如下方式使用它

倉庫工廠的獨立使用
RepositoryFactorySupport factory = … // Instantiate factory here
UserRepository repository = factory.getRepository(UserRepository.class);