建立儲存庫實例

本節涵蓋如何為已定義的儲存庫介面建立實例和 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,以建立適當的 Proxy 來處理查詢方法的調用。每個 Bean 都以從介面名稱衍生的 Bean 名稱註冊,因此 UserRepository 的介面將在 userRepository 下註冊。巢狀儲存庫介面的 Bean 名稱會以其封閉類型名稱作為前綴。基底套件屬性允許使用萬用字元,以便您可以定義掃描套件的模式。

使用篩選器

預設情況下,基礎架構會選取每個擴充位於已配置基底套件下的特定持久化技術 Repository 子介面的介面,並為其建立 Bean 實例。但是,您可能希望更精細地控制為哪些介面建立 Bean 實例。若要執行此操作,請在儲存庫宣告內使用篩選器元素。語意與 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);