[英]Spring Data - How to reuse repository in repository fragment?
更新 :以下使用Spring Boot 2.1.0
我有一個Spring Data存儲庫,並嘗試按照文檔中的片段示例為其提供一些自定義功能。
因此,我向存儲庫添加了一個額外的接口:
public interface UserRepository extends JpaRepository<User, Long>, UserExtraLogic {
User findByFirstNameAndLastName(String firstName, String lastName);
}
使用此自定義界面:
interface UserExtraLogic {
void ensureHasAccess();
}
及其實現:
class UserExtraLogicImpl implements UserExtraLogic {
public void ensureHasAccess() {
}
}
問題是我希望能夠在UserExtraLogicImpl
使用我的存儲庫,這樣我就可以重用findByFirstNameAndLastName
類的查詢方法,而不必自己使用EntityManager
編寫。 所以我嘗試了這個:
class UserExrtaLogicImpl implements UserExtraLogic {
@Autowired
private UserRepository userRepository;
}
但是隨后應用程序無法啟動。 我得到了NullPointerException,但我認為這只是Spring進入嘗試解決這些依賴關系的周期。
我想做的事可能嗎? 還有另一種方法嗎?
您可以使用ObjectFactory<T>
(Spring概念)或Provider<T>
(標准Java API)延遲加載存儲庫。
class UserExrtaLogicImpl implements UserExtraLogic {
@Autowired
private ObjectFactory<UserRepository> userRepository;
public void soSomething() {
userRepository().getObject().findById(xxx);
}
}
我有完全相同的代碼模式,並且在最近的項目中遇到了相同的問題,最后通過使用@Lazy
來懶惰初始化UserRepository
來解決它:
class UserExrtaLogicImpl implements UserExtraLogic {
@Lazy
@Autowired
private UserRepository userRepository;
}
從文檔
如果您使用的是Spring XML配置,則應具有以下內容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jpa:repositories base-package="com.acme.repositories" />
</beans>
如果您使用的是Java配置,則應具有以下配置:
@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {
@Bean
EntityManagerFactory entityManagerFactory() {
// …
}
}
另外,您需要在存儲庫上添加@Repository
批注:
@Repository
public interface UserRepository extends JpaRepository<User, Long>, UserExtraLogic {
User findByFirstNameAndLastName(String firstName, String lastName);
}
說明
從文檔
使用
repositories
元素可以按“創建存儲庫實例”中所述查找Spring Data存儲庫 。 除此之外,它還為所有使用@Repository
注釋的bean激活持久性異常轉換,以將JPA持久性提供程序引發的異常轉換為Spring的DataAccessException
層次結構。
請在文檔中對此加以注意。
Extending the fragment interface with your repository interface combines the CRUD and custom functionality and makes it available to clients.
擴展片段接口時,最終的存儲庫也將包括該接口。 那是它的好處。 如果您想訪問原始存儲庫邏輯,我可以為您推薦3種方法。
不要包括循環依賴,因為這不是一個好習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.