建立 Repository 實例

本節說明如何為已定義的 repository 介面建立實例和 bean 定義。

Java 組態

在 Java 組態類別上使用 store 專用的 @EnableMongoRepositories 註解,以定義 repository 啟用的組態。如需 Spring 容器的基於 Java 組態的介紹,請參閱 Spring 參考文件中的 JavaConfig

啟用 Spring Data repositories 的範例組態如下

基於註解的 repository 組態範例
@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {

  @Bean
  EntityManagerFactory entityManagerFactory() {
    // …
  }
}
前面的範例使用 JPA 專用的註解,您需要根據您實際使用的 store 模組來變更它。這同樣適用於 EntityManagerFactory bean 的定義。請參閱涵蓋 store 專用組態的章節。

XML 組態

每個 Spring Data 模組都包含一個 repositories 元素,可讓您定義 Spring 為您掃描的基礎套件,如下列範例所示

透過 XML 啟用 Spring Data 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 被指示掃描 com.acme.repositories 及其所有子套件,以尋找擴展 Repository 或其子介面的介面。對於找到的每個介面,基礎架構會註冊特定於持久化技術的 FactoryBean,以建立處理查詢方法調用的適當代理。每個 bean 都以從介面名稱衍生的 bean 名稱註冊,因此 UserRepository 的介面將在 userRepository 下註冊。巢狀 repository 介面的 Bean 名稱會加上其封閉類型名稱的前綴。基礎套件屬性允許使用萬用字元,以便您可以定義掃描套件的模式。

使用篩選器

預設情況下,基礎架構會選取每個擴展特定於持久化技術的 Repository 子介面的介面,這些介面位於配置的基礎套件下,並為其建立 bean 實例。但是,您可能希望更精細地控制為哪些介面建立 bean 實例。為此,請在 repository 宣告中使用篩選器元素。語意與 Spring 元件篩選器中的元素完全等效。 有關詳細資訊,請參閱 Spring 參考文件 了解這些元素。

例如,若要將某些介面從實例化為 repository bean 中排除,您可以使用下列組態

使用篩選器
  • Java

  • XML

@Configuration
@EnableMongoRepositories(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 容器外部使用 repository 基礎架構,例如,在 CDI 環境中。您仍然需要在類別路徑中包含一些 Spring 程式庫,但通常,您也可以以程式設計方式設定 repositories。提供 repository 支援的 Spring Data 模組隨附特定於持久化技術的 RepositoryFactory,您可以如下使用它

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