自定義 Repository 實現
Spring Data 提供了多種選項,只需少量編碼即可建立查詢方法。但當這些選項不滿足您的需求時,您也可以為 Repository 方法提供自己的自定義實現。本節介紹如何實現這一點。
自定義單個 Repository
要使用自定義功能豐富 Repository,您必須首先為自定義功能定義一個分片介面和實現,如下所示:
interface CustomizedUserRepository {
void someCustomMethod(User user);
}
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
@Override
public void someCustomMethod(User user) {
// Your custom implementation
}
}
與分片介面對應的類名中最重要的是 |
從歷史上看,Spring Data 自定義 Repository 實現的發現遵循一種命名模式,該模式從 Repository 中派生出自定義實現類名,這實際上只允許一個自定義實現。 與 Repository 介面位於同一包中、名稱與Repository 介面名稱加上實現字尾匹配的型別,會被視為自定義實現並按自定義實現處理。遵循該名稱的類可能導致意外行為。 我們認為單一自定義實現命名已過時,建議不再使用此模式。請遷移到基於分片的程式設計模型。 |
實現本身不依賴於 Spring Data,可以是常規的 Spring Bean。因此,您可以使用標準的依賴注入行為來注入對其他 Bean(例如 JdbcTemplate
)的引用,參與切面等。
然後,您可以讓您的 Repository 介面繼承該分片介面,如下所示:
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {
// Declare query methods here
}
透過讓 Repository 介面繼承分片介面,將 CRUD 和自定義功能結合起來,並使其對客戶端可用。
Spring Data Repository 透過使用形成 Repository 組合的分片來實現。分片包括基礎 Repository、功能切面(例如 Querydsl)以及自定義介面及其實現。每次向 Repository 介面新增一個介面時,您都透過新增一個分片來增強組合。基礎 Repository 和 Repository 切面實現由每個 Spring Data 模組提供。
以下示例展示了自定義介面及其實現
interface HumanRepository {
void someHumanMethod(User user);
}
class HumanRepositoryImpl implements HumanRepository {
@Override
public void someHumanMethod(User user) {
// Your custom implementation
}
}
interface ContactRepository {
void someContactMethod(User user);
User anotherContactMethod(User user);
}
class ContactRepositoryImpl implements ContactRepository {
@Override
public void someContactMethod(User user) {
// Your custom implementation
}
@Override
public User anotherContactMethod(User user) {
// Your custom implementation
}
}
以下示例展示了繼承 CrudRepository
的自定義 Repository 介面
interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {
// Declare query methods here
}
Repository 可以由多個自定義實現組成,這些實現按其宣告順序匯入。自定義實現比基礎實現和 Repository 切面具有更高的優先順序。此順序允許您覆蓋基礎 Repository 和切面方法,並在兩個分片提供相同方法簽名時解決歧義。Repository 分片不僅限於在單個 Repository 介面中使用。多個 Repository 可以使用一個分片介面,從而允許您在不同 Repository 之間重用定製。
以下示例展示了一個 Repository 分片及其實現
save(…)
的分片interface CustomizedSave<T> {
<S extends T> S save(S entity);
}
class CustomizedSaveImpl<T> implements CustomizedSave<T> {
@Override
public <S extends T> S save(S entity) {
// Your custom implementation
}
}
以下示例展示了使用上述 Repository 分片的 Repository
interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}
interface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {
}
配置
Repository 基礎設施會掃描找到 Repository 的包下的類,嘗試自動檢測自定義實現分片。這些類需要遵循命名約定,即附加一個字尾,預設為 Impl
。
以下示例展示了一個使用預設字尾的 Repository 和一個為字尾設定自定義值的 Repository
-
Java
-
XML
@EnableJpaRepositories(repositoryImplementationPostfix = "MyPostfix")
class Configuration { … }
<repositories base-package="com.acme.repository" />
<repositories base-package="com.acme.repository" repository-impl-postfix="MyPostfix" />
上例中的第一個配置嘗試查詢名為 com.acme.repository.CustomizedUserRepositoryImpl
的類作為自定義 Repository 實現。第二個示例嘗試查詢 com.acme.repository.CustomizedUserRepositoryMyPostfix
。
歧義的解決
如果在不同包中找到多個類名匹配的實現,Spring Data 將使用 Bean 名稱來確定使用哪一個。
考慮到前面所示的 CustomizedUserRepository
的以下兩個自定義實現,將使用第一個實現。其 Bean 名稱為 customizedUserRepositoryImpl
,與分片介面 (CustomizedUserRepository
) 名稱加上字尾 Impl
匹配。
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
// Your custom implementation
}
@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
// Your custom implementation
}
如果您使用 @Component("specialCustom")
註解 UserRepository
介面,則 Bean 名稱加上 Impl
將與 com.acme.impl.two
中為 Repository 實現定義的名稱匹配,並使用它而不是第一個實現。
手動裝配
如果您的自定義實現僅使用基於註解的配置和自動裝配,上述方法效果很好,因為它被視為任何其他 Spring Bean。如果您的實現分片 Bean 需要特殊裝配,您可以根據上一節中描述的約定宣告並命名該 Bean。然後,基礎設施將按名稱引用手動定義的 Bean 定義,而不是自己建立一個。以下示例展示瞭如何手動裝配自定義實現
-
Java
-
XML
class MyClass {
MyClass(@Qualifier("userRepositoryImpl") UserRepository userRepository) {
…
}
}
<repositories base-package="com.acme.repository" />
<beans:bean id="userRepositoryImpl" class="…">
<!-- further configuration -->
</beans:bean>
使用 spring.factories 註冊分片
如配置一節所述,基礎設施只會在 Repository 基礎包內自動檢測分片。因此,位於其他位置或希望由外部歸檔檔案貢獻的分片,如果它們沒有共享公共名稱空間,將無法被找到。在 spring.factories
中註冊分片允許您繞過此限制,如下節所述。
想象一下,您希望利用文字搜尋索引為您的組織提供一些可跨多個 Repository 使用的自定義搜尋功能。
首先,您需要的是分片介面。請注意通用引數 <T>
,它用於使分片與 Repository 域型別對齊。
public interface SearchExtension<T> {
List<T> search(String text, Limit limit);
}
假設實際的全文搜尋透過註冊為上下文中 Bean
的 SearchService
提供,以便您可以在我們的 SearchExtension
實現中消費它。執行搜尋所需的一切是集合(或索引)名稱以及一個將搜尋結果轉換為實際域物件的物件對映器,如下所示。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Limit;
import org.springframework.data.repository.core.RepositoryMethodContext;
class DefaultSearchExtension<T> implements SearchExtension<T> {
private final SearchService service;
DefaultSearchExtension(SearchService service) {
this.service = service;
}
@Override
public List<T> search(String text, Limit limit) {
return search(RepositoryMethodContext.getContext(), text, limit);
}
List<T> search(RepositoryMethodContext metadata, String text, Limit limit) {
Class<T> domainType = metadata.getRepository().getDomainType();
String indexName = domainType.getSimpleName().toLowerCase();
List<String> jsonResult = service.search(indexName, text, 0, limit.max());
return jsonResult.stream().map(…).collect(toList());
}
}
在上面的示例中,使用 RepositoryMethodContext.getContext()
來檢索實際方法呼叫的元資料。RepositoryMethodContext
暴露了附加到 Repository 的資訊,例如域型別。在這種情況下,我們使用 Repository 域型別來標識要搜尋的索引名稱。
暴露呼叫元資料是昂貴的,因此預設情況下是停用的。要訪問 RepositoryMethodContext.getContext()
,您需要建議負責建立實際 Repository 的 Repository 工廠暴露方法元資料。
-
標記介面
-
Bean Post Processor
將 RepositoryMetadataAccess
標記介面新增到分片實現將觸發基礎設施併為使用該分片的 Repository 啟用元資料暴露。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Limit;
import org.springframework.data.repository.core.support.RepositoryMetadataAccess;
import org.springframework.data.repository.core.RepositoryMethodContext;
class DefaultSearchExtension<T> implements SearchExtension<T>, RepositoryMetadataAccess {
// ...
}
可以透過 BeanPostProcessor
直接在 Repository 工廠 Bean 上設定 exposeMetadata
標誌。
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
import org.springframework.lang.Nullable;
@Configuration
class MyConfiguration {
@Bean
static BeanPostProcessor exposeMethodMetadata() {
return new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if(bean instanceof RepositoryFactoryBeanSupport<?,?,?> factoryBean) {
factoryBean.setExposeMetadata(true);
}
return bean;
}
};
}
}
請不要直接複製/貼上上述內容,而是考慮您的實際用例,這可能需要更細粒度的方法,因為上述方法將簡單地在每個 Repository 上啟用該標誌。
在分片宣告和實現都到位後,您可以在 META-INF/spring.factories
檔案中註冊擴充套件,並在需要時打包。
META-INF/spring.factories
中註冊分片com.acme.search.SearchExtension=com.acme.search.DefaultSearchExtension
現在您可以開始使用您的擴充套件了;只需將介面新增到您的 Repository 中即可。
import com.acme.search.SearchExtension;
import org.springframework.data.repository.CrudRepository;
interface MovieRepository extends CrudRepository<Movie, String>, SearchExtension<Movie> {
}
定製基礎 Repository
上一節中描述的方法需要定製每個 Repository 接口才能定製基礎 Repository 的行為,以便所有 Repository 都受到影響。若要改為更改所有 Repository 的行為,您可以建立一個擴充套件特定持久化技術的基礎 Repository 類的實現。然後,此類別將作為 Repository 代理的自定義基礎類,如以下示例所示:
class MyRepositoryImpl<T, ID>
extends SimpleJpaRepository<T, ID> {
private final EntityManager entityManager;
MyRepositoryImpl(JpaEntityInformation entityInformation,
EntityManager entityManager) {
super(entityInformation, entityManager);
// Keep the EntityManager around to used from the newly introduced methods.
this.entityManager = entityManager;
}
@Override
@Transactional
public <S extends T> S save(S entity) {
// implementation goes here
}
}
該類需要有一個超類建構函式,該建構函式由特定儲存的 Repository 工廠實現使用。如果基礎 Repository 類有多個建構函式,請覆蓋接受 EntityInformation 以及特定儲存基礎設施物件(例如 EntityManager 或模板類)的建構函式。 |
最後一步是讓 Spring Data 基礎設施知道定製的基礎 Repository 類。在配置中,您可以透過使用 repositoryBaseClass
來實現,如下例所示:
-
Java
-
XML
@Configuration
@EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
base-class="….MyRepositoryImpl" />